超级甜的sync语法糖你尝过了吗?

为什么sync超级甜呢?

因为他非常好用啊,可以使用sync让子组件改变父组件传过来的值,也就是可以在子组件中改变props中的变量了,嘿嘿,这样就可以子父组件同步了。

具体怎么使用呢?

首先父组件传值过来,并且在传值的时候添加.sync后缀

<son :fromFather.sync="fromSon"></son>
data(){
    
    
  return{
    
    
     fromSon:"父组件的值"
   }
},

子组件接收,并设置改变传过来的fromFather变量

//props
props: {
    
    
  fromFather: {
    
    
    type: String,
    default: ''
  },
},
//页面
<el-button @click="change">改变他</el-button>
<div>{
    
    {
    
    fromFather}}</div>

//按钮的change事件来改变fromFather的值
change() {
    
    
	this.$emit('update:fromFather',"我可以改变了!!")
}

最后实现的结果:
在这里插入图片描述
所以这样我们就可以在子组件中改变父组件props传过来的值了。

实现的原理是什么呢?

其实就是我们在父组件传值的时候,还给传的变量设置了一个子组件传值给父组件的事件——update:fromFather。所以实现了可以双向改变。

猜你喜欢

转载自blog.csdn.net/make_1998/article/details/107081121