vue双向数据绑定

一:v-model

父组件引用子组件时,可以使用 v-model="params"  绑定一个变量,

在子组件中,需要使用props去接收一个value变量,即父组件绑定到的params的值

在子组件中,使用this.$emit("input" , someData); 可以触发父组件的input事件,someData是参数,它的值会赋给父组件的params的变量。

 

这种写法是一种简化的写法,是vue的语法糖。他也可以写成

 

 父组件:

<v-children v-bind:value="params"  @input="input(params)"></v-children>

子组件:

this.$emit("input" , someDta);

二: 自定义传值

父组件:

    <myc :names='names' @changeValChild="changeVal"></myc>

或者:
   <myc names='names' @changeValChild="changeVal"></myc>

//区别:前者‘names'是一个变量,后者names会当作字符串处理

methods: {
  changeVal () {
    flag ? this.names = '修改前' : this.names = '修改后的值'
    flag = !flag
  }
}

 

子组件:

 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版本之后又恢复使用

原文地址:https://www.cnblogs.com/summer0319/p/6649065.html