vue3觸發(fā)父組件兩種寫法
vue3觸發(fā)父組件兩種寫法
1、正常寫法
子組件:
import { defineComponent } from 'vue'; export default defineComponent({ emits: ["testEmi"], setup(props, context) { const changeCollapse = () => { //觸發(fā)父組件事件 context.emit("testEmi") } return { testEmi } } })
父組件:
<test @testEmit="testEmi" />
2、 語法糖寫法
子組件:
const emit = defineEmits(["downloadTemp"]); const downloadTemp = () => { emit("downloadTemp", "12"); };
父組件:
<UpDownload @downloadTemp="downloadTempSms"/>
在 <script setup>
中必須使用 defineProps
和 defineEmits
API 來聲明 props
和 emits
補(bǔ)充:vue子組件調(diào)用父組件的3種方法,超實(shí)用
1. 直接在子組件中通過this.$parent.event來調(diào)用父組件的方法
父組件:
<template> <div> <child></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件:
<template> <div> <button @click="childMethod()">點(diǎn)擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$parent.fatherMethod(); } } };
2. 在子組件里用$emit向父組件觸發(fā)一個(gè)事件,父組件監(jiān)聽這個(gè)事件
父組件:
<template> <div> <child @fMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod(data) { console.log(data); } } }; </script>
子組件:
<template> <div> <button @click="childMethod()">點(diǎn)擊</button> </div> </template> <script> export default { methods: { childMethod() { this.$emit('fMethod',data); } } }; </script>
3. 父組件把方法傳入子組件中,在子組件里直接調(diào)用
父組件:
<template> <div> <child :fatherMethod="fatherMethod"></child> </div> </template> <script> import child from '~/components/dam/child'; export default { components: { child }, methods: { fatherMethod() { console.log('測試'); } } }; </script>
子組件:
<template> <div> <button @click="childMethod()">點(diǎn)擊</button> </div> </template> <script> export default { props: { fatherMethod: { type: Function, default: null } }, methods: { childMethod() { if (this.fatherMethod) { this.fatherMethod(); } } } }; </script>
到此這篇關(guān)于vue3觸發(fā)父組件兩種寫法的文章就介紹到這了,更多相關(guān)vue3觸發(fā)父組件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Vue2的獨(dú)立構(gòu)建與運(yùn)行時(shí)構(gòu)建的差別(詳解)
下面小編就為大家分享一篇基于Vue2的獨(dú)立構(gòu)建與運(yùn)行時(shí)構(gòu)建的差別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2017-12-12Vue中通過vue-router實(shí)現(xiàn)命名視圖的問題
這篇文章主要介紹了在Vue中通過vue-router實(shí)現(xiàn)命名視圖,本文給大家提到了vue-router的原理解析,給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04vue 實(shí)現(xiàn)路由跳轉(zhuǎn)時(shí)更改頁面title
今天小編就為大家分享一篇vue 實(shí)現(xiàn)路由跳轉(zhuǎn)時(shí)更改頁面title,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11Vue的路由動(dòng)態(tài)重定向和導(dǎo)航守衛(wèi)實(shí)例
下面小編就為大家分享一篇Vue的路由動(dòng)態(tài)重定向和導(dǎo)航守衛(wèi)實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03webpack配置導(dǎo)致字體圖標(biāo)無法顯示的解決方法
下面小編就為大家分享一篇webpack配置導(dǎo)致字體圖標(biāo)無法顯示的解決方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03