詳解vue中在父組件點擊按鈕觸發(fā)子組件的事件
我把這個實例分為幾個步驟解讀:
1、父組件的button元素綁定click事件,該事件指向notify方法
2、給子組件注冊一個ref=“child”
3、父組件的notify的方法在處理時,使用了$refs.child把事件傳遞給子組件的parentMsg方法,同時攜帶著父組件中的參數(shù)msg
4、子組件接收到父組件的事件后,調用了parentMsg方法,把接收到的msg放到message數(shù)組中
父組件
<template>
<div id="app">
<!--父組件-->
<input v-model="msg" />
<button v-on:click="notify">廣播事件</button>
<!--子組件-->
<popup ref="child"></popup>
</div>
</template>
<script>
import popup from "@/components/popup";
export default {
name: "app",
data: function () {
return {
msg: "",
};
},
components: {
popup,
},
methods: {
notify: function () {
if (this.msg.trim()) {
this.$refs.child.parentMsg(this.msg);
}
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子組件
<template>
<div>
<ul>
<li v-for="item in messages">父組件輸入了:{{ item }}</li>
</ul>
</div>
</template>
<style>
body {
background-color: #ffffff;
}
</style>
<script>
export default {
name: "popup",
data: function () {
return {
messages: [],
};
},
methods: {
parentMsg: function (msg) {
this.messages.push(msg);
},
},
};
</script>
到此這篇關于詳解vue中在父組件點擊按鈕觸發(fā)子組件的事件的文章就介紹到這了,更多相關vue 父組件觸發(fā)子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue + AnimeJS實現(xiàn)3d輪播圖的詳細代碼
輪播圖在開發(fā)中是經(jīng)常用到的,3D輪播圖是其中最常用的一種,所以在這篇文章中將給大家介紹Vue + AnimeJS實現(xiàn)3d輪播圖,文中有詳細的代碼示例供大家參考,具有一定的參考價值,需要的朋友可以參考下2024-01-01
vue項目本地開發(fā)使用Nginx配置代理后端接口問題
這篇文章主要介紹了vue項目本地開發(fā)使用Nginx配置代理后端接口問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12

