vue3父子組件相互調用方法詳解
更新時間:2024年05月14日 08:50:41 作者:前端開發(fā)菜鳥的自我修養(yǎng)
在vue3項目開發(fā)中,我們常常會遇到父子組件相互調用的場景,下面主要以setup語法糖格式詳細聊聊父子組件那些事兒,并通過代碼示例介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下
1、前言
在vue3項目開發(fā)中,我們常常會遇到父子組件相互調用的場景,下面主要以setup語法糖格式詳細聊聊父子組件那些事兒
2、子組件調用父組件方法(setup組合式)
2.1 父組件Father.vue
<template>
<child @sayHello="handle" />
</template>
<script setup>
import Child from './components/child.vue';
const handle = () => {
console.log('子組件調用了父組件的方法')
}
</script>2.2 子組件Child.vue
<template>
<view>我是子組件</view>
<button @click="sayHello">調用父組件的方法</button>
</template>
<script setup>
const emit = defineEmits(["sayHello"])
const sayHello = () => {
emit('Hello World')
}
</script>3、父組件調用子組件方法(setup組合式)
3.1 子組件Child.vue
<template>
<div>我是子組件</div>
</template>
<script setup>
// 第一步:定義子組件的方法
const sayHello = (value) => {
console.log(value)
}
// 第二部:暴露方法
defineExpose({
sayHello
})
</script>3.2 父組件Father.vue
<template>
<button @click="getChild">觸發(fā)子組件方法</button>
<child ref="childRef" />
</template>
<script setup>
import Child from './components/child.vue'
// 定義與 ref 同名變量
const childRef = ref(null)
const getChild = () => {
// 調用子組件的方法或者變量,通過value
childRef.value.hello("hello world!");
}
</script>4、簡單說下選項式API的寫法
不推薦,vue3能寫組合式就寫組合式
4.1 父組件 app.vue
<template>
<div class="itxst">
<!-- 使用 ref 命令 -->
<child ref="childComp"/>
<button @click="onClick">點擊試一試</button>
</div>
</template>
<script >
import child from "./child.vue";
export default {
name: "app",
//注冊組件
components: {
child,
},
methods: {
onClick: function () {
//獲取到 子組件的 數據
let msg = this.$refs.childComp.title;
//執(zhí)行了子組件的 play方法
this.$refs.childComp.play();
},
},
};
</script> 4.2 子組件 child.vue
<template>
<div class="itxst">
{{ title }}
</div>
</template>
<script>
//選項式默認當前實例是全部暴露
export default {
name: "demo",
//默認全部暴露 也可以通過expose控制那些需要暴露
//expose: ['play'],
data() {
return {
title: "www.itxst.com",
};
},
methods: {
play: function () {
this.title = "你調用了子組件的方法";
},
},
};
</script>到此這篇關于vue3父子組件相互調用方法詳解的文章就介紹到這了,更多相關vue3父子組件相互調用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue3.0中給自己添加一個vue.config.js配置文件
這篇文章主要介紹了vue3.0中給自己添加一個vue.config.js配置文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
基于vue2.0+vuex+localStorage開發(fā)的本地記事本示例
這篇文章主要介紹了基于vue2.0+vuex+localStorage開發(fā)的本地記事本示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-02-02
詳解vue beforeEach 死循環(huán)問題解決方法
這篇文章主要介紹了vue beforeEach 死循環(huán)問題解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02
vue實現(xiàn)樣式之間的切換及vue動態(tài)樣式的實現(xiàn)方法
這篇文章主要介紹了vue中如何實現(xiàn)樣式之間的切換及vue動態(tài)樣式的實現(xiàn)方法,本文給大家介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2017-12-12

