vue單頁開發時經常需要父子組件之間傳值,自己用過但是不是很熟練,這里我抽空整理了一下思路,寫寫自己的總結。
GitHub地址:https://github.com/leileibrother/wechat-vue
文件目錄如下圖,example.vue是父組件,exampleChild.vue是子組件。
父組件引入子組件,父組件html的代碼如下:
<template> <div> <h3>這是父組件</h3> <p style="margin: 20px 0;text-align: center;"> <span>子組件傳過來的值是 “{{childValue}}”</span> </p> <example-child v-bind:message="parentMsg" @getChildValue="getValue"></example-child> </div> </template> <script> import exampleChild from './examplechild.vue'; export default { name: "example.vue", components: { exampleChild }, data(){ return { parentMsg:'hello', childValue:'' } }, mounted(){ }, methods: { getValue:function (val) { this.childValue = val; } } } </script> <style scoped> </style>
子組件代碼如下:
<template> <div> <p style="margin: 20px 0;text-align: center;">我是子組件,父組件穿傳過來的值是{{message}}</p> <p style="margin: 20px 0;text-align: center;"> <button @click="send">點擊向父組件傳值</button> </p> </div> </template> <script> export default { name: "exampleChild.vue", props:['message'], data(){ return { } }, mounted(){ }, methods: { send:function () { this.$emit('getChildValue','你好父組件!') } } } </script> <style scoped> </style>
1,父組件向子組件傳值。
在父組件中使用v-bind來綁定數據傳給子組件,如我寫的v-bind:message="parentMsg",把message字段傳給子組件,
在子組件中使用props接收值,如props:['message']
,接收父組件傳過來的message字段,使用{{message}}
就是可以使用父組件傳過來的值了。
2,子組件向父組件傳值。
子向父傳值需要一個“中轉站”,如我寫的getChildValue,命名隨便寫。
在子組件中使用$emit()
來向父組件傳值。第一個參數就是這個“中轉站”,后面的參數是要傳的值,可以是多個。
在父組件中如下,也需要這個中轉站來接收值
getValue是接收子組件值的函數,參數val就是子組件傳過來的值,這樣就可以接收到子組件傳過來的值了。
總結
以上所述是小編給大家介紹的vue單頁開發父子組件傳值思路詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答