初识vue 2.0(5):使用props父子组件通信
在復雜場景中,可以使用專門的狀態(tài)管理模式 Vuex。
簡單的場景中,可以使用一個父組件、若干個子組件來構(gòu)建應用,這樣通信會比使用vuex簡單些:
1. 子組件的 props 選項可以接收父組件傳遞過來的數(shù)據(jù),這是一個單向數(shù)據(jù)流的過程,子組件對props改動,不會影響父組件。
2. 子組件也可以通過自定義事件向父組件傳遞數(shù)據(jù)。父組件監(jiān)聽自定義事件,子組件使用 $emit 觸發(fā)這個事件。
?
?父組件:
1. 在父組件hello中引入子組件son,并注冊在components中;
2. 在父組件hello的模版中,通過自定義標簽引入子組件son模版。
3. 通過子組件son模版標簽的自定義屬性msg傳遞數(shù)據(jù),傳遞動態(tài)數(shù)據(jù)使用 :msg (即:v-bind:msg),否則直接使用msg即可。
4. 在子組件模版標簽中監(jiān)聽自定義事件receive(@receive 即 v-on:receive),監(jiān)聽子組件傳遞的信息。
1 <template> 2 <div class="hello"> 3 <son :msg="msg" @receive="receive"></son> 4 <p>{{ answer }}</p> 5 </div> 6 </template> 7 8 <script> 9 import Son from '@/components/Son' 10 export default { 11 name: 'hello', 12 components: { 13 Son 14 }, 15 data () { 16 return { 17 msg:'我是hello模塊傳遞給子模塊的信息', 18 answer:'' 19 } 20 }, 21 methods: { 22 receive(answer) { 23 this.answer = answer; 24 } 25 } 26 } 27 </script>?
子組件:
為了模擬數(shù)據(jù)傳遞過程,在子組件中構(gòu)建click事件,用于觸發(fā)子組件對父組件的數(shù)據(jù)傳遞。
1. 子組件通過props接收父組件傳遞的數(shù)據(jù)msg。可以直接通過模版標簽{{ msg }}顯示于模版中,也可以通過this.msg獲取。
2. 點擊回復按鈕,調(diào)用send方法,通過$emit,觸發(fā)父組件中的自定義事件receive,將數(shù)據(jù)answer傳遞給父組件。
1 <template> 2 <div class="son"> 3 <p>{{ msg }} <button v-on:click="send">回復</button></p> 4 </div> 5 </template> 6 7 <script> 8 export default { 9 name: "son", 10 props: ["msg"], 11 data () { 12 return { 13 answer:"我是Son模塊傳遞給父模塊的信息" 14 } 15 }, 16 methods: { 17 send() { 18 this.$emit("receive",this.answer); 19 } 20 } 21 } 22 </script>?還有一種組件通信方式是event bus,可以進行兄弟組件之間數(shù)據(jù)傳遞,有時間在分享下。 ^_^
轉(zhuǎn)載于:https://www.cnblogs.com/phptree/p/9058125.html
總結(jié)
以上是生活随笔為你收集整理的初识vue 2.0(5):使用props父子组件通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue.js的使用总结
- 下一篇: Vue.js中的MVVM