深入理解vue .sync修饰符

曾经终败给现在 2023-08-17 17:39 165阅读 0赞

.sync是vue中用于实现简单的“双向绑定”的语法糖,在平时的开发中是非常使用的。

vue的prop是单向下行绑定:父级的prop的更新会向下流动到子组件中,但是反过来不行。可是有些情况,我们需要对prop进行“双向绑定”。这个时候,就可以用.sync来解决

.sync用法

  1. <text-document :title.sync="doc.title"></text-document>
  2. 当子组件需要更新 title 的值时,它需要显式地触发一个更新事件:
  3. this.$emit('update:title', newValue)

这样title的属性在子组件内部更新,父组件也能感知的到,实现了“双向绑定”。

.sync应运实例

  1. <template>
  2. <div class="details">
  3. <myComponent :show.sync='valueChild' style="padding: 30px 20px 30px 5px;border:1px solid #ddd;margin-bottom: 10px;"></myComponent>
  4. <button @click="changeValue">toggle</button>
  5. </div>
  6. </template>
  7. <script>
  8. import Vue from 'vue'
  9. Vue.component('myComponent', {
  10. template: `<div v-if="show">
  11. <p>默认初始值是{
  12. {show}},所以是显示的</p>
  13. <button @click.stop="closeDiv">关闭</button>
  14. </div>`,
  15. props:['show'],
  16. methods: {
  17. closeDiv() {
  18. this.$emit('update:show', false); //触发 input 事件,并传入新值
  19. }
  20. }
  21. })
  22. export default{
  23. data(){
  24. return{
  25. valueChild:true,
  26. }
  27. },
  28. methods:{
  29. changeValue(){
  30. this.valueChild = !this.valueChild
  31. }
  32. }
  33. }
  34. </script>

如果未触发事件 this.$emit(‘update:show’, false); 则外部感知不到子组件内部对show的改变,依然认为此事的值是true,导致弹框点击打开一次之后,后面再不会打开。

转载于:https://www.cnblogs.com/00feixi/p/11526057.html

发表评论

表情:
评论列表 (有 0 条评论,165人围观)

还没有评论,来说两句吧...

相关阅读

    相关 vue之.sync修饰符

    根据VUE官方文档所述,.sync修饰符用来prop双向绑定,而.sync修饰符类似v-model,只是一个语法糖 ![在这里插入图片描述][watermark_type_

    相关 .sync修饰符

    第一步:先用一句话解释 .sync修饰符可以实现子组件与父组件的双向绑定,并且可以实现子组件同步修改父组件的值。 第二步:具体解释 一般情况下,想要实现父子组件间