一:v-modelvue
父組件引用子組件時,能夠使用 v-model="params" 綁定一個變量,this
在子組件中,須要使用props去接收一個value變量,即父組件綁定到的params的值spa
在子組件中,使用this.$emit("input" , someData); 能夠觸發父組件的input事件,someData是參數,它的值會賦給父組件的params的變量。code
這種寫法是一種簡化的寫法,是vue的語法糖。他也能夠寫成component
父組件: <v-children v-bind:value="params" @input="input(params)"></v-children> 子組件: this.$emit("input" , someDta);
二: 自定義傳值orm
父組件:blog
<myc :names='names' @changeValChild="changeVal"></myc> 或者: <myc names='names' @changeValChild="changeVal"></myc> //區別:前者‘names'是一個變量,後者names會看成字符串處理
methods: {
changeVal () {
flag ? this.names = '修改前' : this.names = '修改後的值'
flag = !flag
}
}事件
子組件:ip
1 <h1>{{ names }}</h1> 2 <h2>my components</h2> 3 <button @click='letParentchangeVal'>修改</button> 4 5 6 7 methods: { 8 letParentchangeVal () { 9 this.$emit('changeValChild') 10 } 11 }
三:雙向數據綁定字符串
1 //子組件 2 3 <template> 4 <div class="myc"> 5 <h1>{{ getName }}</h1> 6 <input type="text" v-model='getName'> 7 <input type="text" v-model='names'> 8 <button @click='letParentchangeVal'>修改</button> 9 10 </div> 11 </template> 12 13 <script> 14 export default { 15 name: 'myc', 16 data () { 17 return { 18 getName: this.names 19 } 20 }, 21 props: { 22 names: { 23 type: String 24 // default: '默認值' 25 } 26 }, 27 watch: { 28 getName (val) { 29 // 設置監聽,若是改變就更新 30 this.$emit('update:names', val) 31 } 32 }, 33 methods: { 34 letParentchangeVal () { 35 this.$emit('changeValChild') 36 } 37 } 38 } 39 </script>
1 // 父組件 2 3 <template> 4 <div class="hello"> 5 6 <h1>{{ names }}</h1> 7 <h2>父組件</h2> 8 9 <myc :names.sync='names' @changeValChild="changeVal"></myc> 10 </div> 11 </template> 12 13 <script> 14 import myc from './mycomponent/page' 15 let flag = false 16 export default { 17 name: 'hello', 18 components: { 19 myc 20 }, 21 data () { 22 return { 23 names: '初始化' 24 } 25 }, 26 methods: { 27 changeVal () { 28 flag ? this.names = '修改前' : this.names = '修改後的值' 29 flag = !flag 30 } 31 } 32 } 33 </script> 34 35 <!-- Add "scoped" attribute to limit CSS to this component only --> 36 <style scoped> 37 h1, h2 { 38 font-weight: normal; 39 } 40
.sync 在vue2.0版本廢除,可是在2.3版本以後又恢復使用