詳解vue中在父組件點擊按鈕觸發(fā)子組件的事件
我把這個實例分為幾個步驟解讀:
1、父組件的button元素綁定click事件,該事件指向notify方法
2、給子組件注冊一個ref=“child”
3、父組件的notify的方法在處理時,使用了$refs.child把事件傳遞給子組件的parentMsg方法,同時攜帶著父組件中的參數(shù)msg
4、子組件接收到父組件的事件后,調(diào)用了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>
到此這篇關(guān)于詳解vue中在父組件點擊按鈕觸發(fā)子組件的事件的文章就介紹到這了,更多相關(guān)vue 父組件觸發(fā)子組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue.config.js配置proxy代理產(chǎn)生404錯誤的原因及解決
這篇文章主要介紹了vue.config.js配置proxy代理產(chǎn)生404錯誤的原因及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
Vue Element-UI中el-table實現(xiàn)單選的示例代碼
在element-ui中是為我們準(zhǔn)備好了可直接使用的單選與多選屬性的,本文主要介紹了Vue Element-UI中el-table實現(xiàn)單選的示例代碼,具有一定的參考價值,感興趣的可以了解一下2023-12-12
如何使用vuejs實現(xiàn)更好的Form validation?
如何使用vuejs實現(xiàn)更好的Form validation?這篇文章主要介紹了vue-form插件的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04

