vue中的sync

Hello!大家好今天给大家讲一下我最近了解到的一些新的东西在这里给大家分享一下。

一:.sync
官方推荐使用一种update:my-prop-name 的模式来替代事件触发,目的是为了优雅而不粗鲁的实现父子组件间的双向绑定!先来完成一个小功能:通过父组件按钮将子组件显示出来。
父组件代码(通常的做法):

     <template>
		  <div>
		    <button @click="show = true">我是父组件的按钮</button>
		    <coment-children v-if="show"  @isShow="isShow"></coment-children>
		  </div>
		</template>
		<script>
		import comentChildren from "./children";
		export default {
		  data() {
		    return {
		      show: false
		    };
		  },
		  components: {
		    comentChildren
		  },
		  methods:{
		      isShow(val){this.show = val;}
           }
		};
		</script>

子组件child代码:

     <template>
		  <div style="width:200px;height:200px;background:red;">
		    我是helloWorld模块的子组件
		     <button @click="isShow">我是子组件的按钮点我隐身</button>   //第一种
		     <button @click="$parent.show = false">我是子组件的按钮点我隐身</button>  //第二种(不推荐也不规范)
		  </div>
		</template>
		<script>
		export default {
		  data() {
		    return {};
		  },
		  methods: {
		    isShow() {
		      this.$emit("isShow", false);
		    }
		  }
		};
		</script>

然后咱们改一种方法看看能不能正常运行

    父组件: <coment-children    @update:isShow="show"  v-if="show"/></coment-children>

子组件的emit自然也要做对应调整:

      this.$emit("update:isShow",false);

一切运行正常不报错,咱们最后改成.sync的方法

  父组件:<template>
			  <div>
			    <button @click="show = true">我是父组件的按钮</button>
			    <coment-children v-if="show" :isShow.sync="show"></coment-children>
			  </div>
			</template>
			<script>
			import comentChildren from "./children";
			export default {
			  data() {
			    return {
			      show: false
			    };
			  },
			  components: {
			    comentChildren
			  }
			};
			</script>


  子组件:<template>
				  <div style="width:200px;height:200px;background:red;">
				    我是helloWorld模块的子组件
				    <button @click="$emit('update:isShow',false)">我是子组件的按钮点我隐身</button>
				  </div>
				</template>
				<script>
				export default {
				  data() {
				    return {};
				  }
				};
				</script>

git地址:https://github.com/Liingot/sync.git
注意:.sync官方给出的解释就是一种语法糖的意思
最后:sync只是给大家伙提供了一种与父组件沟通的思路而已!所以在后面日子里,你如果只是单纯的在子组件当中修改父组件的某个数据时,建议使用sync,简单,快捷,不需要在传一个自定义方法来接收了,今天就到这里谢谢大家。

  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值