1、父組件向子組件傳值vue
1.建立子組件,在src/components/文件夾下新建一個child.vueless
2.在child.vue 中建立props,而後新加一個title屬性函數
<template> <div> <h1>child子組件</h1> <div>{{title}}</div> </div> </template> <script> export default { name: 'child', props:["title"], } </script> <style scoped lang="less"> </style>
3.在parent.vue父組件中註冊child組件,並在template中加入child標籤,標籤中綁定title屬性,並在data中賦值this
<template> <div> <h1>parent父組件</h1> <child v-bind:title="parentTitle"></child> </div> </template> <script> import child from './child';//引用子組件 export default { name: 'parent', data(){ return { parentTitle:"hello,child" } }, components:{ child } } </script> <style scoped lang="less"> </style>
父組件向子組件傳值總結:code
2、子組件向父組件傳值component
1.在子組件中建立一個按鈕,給按鈕綁定一個點擊事件事件
2.在響應該點擊事件的函數中使用$emit來觸發一個自定義事件,並傳遞一個參數ip
<template> <div> <h1>child子組件</h1> <button @click="sendMsgToParent">向父組件傳值</button> </div> </template> <script> export default { name: 'child', methods:{ sendMsgToParent(){ this.$emit("listenToChildEvent","this message is from child") } } } </script> <style scoped lang="less"> </style>
3..在父組件中的子標籤中監聽該自定義事件並添加一個響應該事件的處理方法it
<template> <div> <h1>parent父組件</h1> <child v-on:listenToChildEvent="showMsgFromChild"></child> </div> </template> <script> import child from './child';//引用子組件 export default { name: 'parent', data(){ }, components:{ child }, methods:{ showMsgFromChild(msg){ console.log(msg) } } } </script> <style scoped lang="less"> </style>
子組件向父組件傳值總結:console
總之,在通訊中,不管是子組件向父組件傳值仍是父組件向子組件傳值,他們都有一個共同點就是有中間介質,子向父的介質是自定義事件,父向子的介質是props中的屬性。