1.父元件向子元件傳值
定義父子元件 并在父元件中引入注冊子元件
< template > < div > < child v-bind:greetMsg=" name" ></ child > </ div > </ template > < script > import Child from '../components/child.vue' export default { data(){ return { name: "你好,我是爸爸" } }, components:{ Child } } </ script > < style > </ style >
定義子元件
< template > < div >{{ greetMsg}} </ div > </ template > < script > export default { props:[ 'greetMsg' ] } </ script > < style > </ style >
頁面顯示效果是
父元件向子元件傳值是利用props
子元件中的注意事項:props:['greetMsg'],注意props後面是[]數組可以接收多個值,不是{}。
且此處的greetMsg用greet-msg會報錯,記住需用駝峰法命名
父元件中的注意事項:資料是在父元件中定義
需先引入再注冊Child
使用的是v-bind:greetMsg="name",此處的greetMsg需與子元件中props中的一緻
2.子元件向父元件傳值
定義父元件
< template > < div > < child v-on:send=" getMessage" ></ child > < div >{{ msg}} </ div > </ div > </ template > < script > import Child from '../components/child' export default { components:{ Child }, data(){ return { msg: '' } }, methods:{ getMessage( greetMsg){ this. msg= greetMsg } } } </ script > < style > </ style >
定義子元件
< template > < div > < button @click=" sendMessage" >點選一下,向父元件傳值 </ button > </ div > </ template > < script > export default { data(){ return{ sayName: "您好,我叫小明,我是您孩子" } }, methods:{ sendMessage(){ this. $emit( 'send', this. sayName) } } } </ script > < style > </ style >
點選按鈕後,頁面顯示結果是
子元件向父元件傳值是利用在子元件中使用$emit在父元件中綁定事件來實作
子元件中的注意事項:需在子元件中定義資料
綁定事件,比如@click事件,再在methods裡面定義該事件this.$emit('send',this.sayName)
父元件中的注意事項:引入注冊子元件
綁定相應的方法 v-on:send注意此處的send需與子元件中的this.$emit()中的第一個參數一緻,記住需使用駝峰法命名