Vue中子组件与父组件之间的双向绑定

这里写一个小的demo就是通过一个Button子组件实现value的加一减一,如图

Vue中子组件与父组件之间的双向绑定_第1张图片

首先给个根节点,id为app的div

		

首先全局注册组件my-com:

		
		Vue.component('my-com',{
			template:'
' })

 
  

new一个vue对象:

		
		
		new Vue({
			el:'#app'
		})


 
  

给组件my-com, 一个props以便父组件向子组件传数据,设置currentvalue为初始数据,添加绑定事件handleClick

		
		Vue.component('my-com',{
			props:{
				value:{
					type:Number
				}
			},
			template:'
{{currentvalue}}
', data(){ return{ currentvalue:this.value } }, methods:{ handleClick(){ this.currentvalue++; this.$emit('input',this.currentvalue);//用于子组件向父组件触发事件,这里前面必须填input } } });

 在父组件里添加value字段 
  

		
		new Vue({
	 		el:'#app',
			data:{
				value:1
			},
			methods:{
				handleReduce(){
					this.value--;
				}
			}
		})

 
  

在div里添加放入my-com组件,并且双向绑定value

		

 通过以上的操作,我们的加就写好了,现在我们写减,通过父组件的改变,同样改变子组件里的值 
  

在div里添加一个button,前面放一个value值用来观察数据变化,绑定一个handleReduce事件

		
{{value}}
在父组件里添加handleReduce方法

		
		new Vue({
			el:'#app',
			data:{
				value:1
			},
			methods:{
				handleReduce(){
					this.value--;
				}
			}
		})

 然后,这样减就写好了但是我们发现一个问题,就是点击减之后,子组件里的值不能跟着变化,如图: 
  

那怎么办呢?我们要在子组件中加入watch来监听变化重新赋值!

			watch:{
				value(val){
					this.currentvalue=val;
				}
			}

 
  








你可能感兴趣的:(vue)