美文网首页
使用.sync 来让子组件修改父组件的值

使用.sync 来让子组件修改父组件的值

作者: 海之深处爱之港湾 | 来源:发表于2021-07-09 09:56 被阅读0次

    在父组件中,直接在需要传递的属性后面加上.sync

    <child-component :word.sync="word"></child-component>
    

    在子组件中

    <template>
      <div>
        <h3>{{word}}</h3>
        <input type="text" v-model="str" />
      </div>
    </template>
    <script>
    export default {
      props: {
        word: {
          type: String,
          default: '',
        },
      },
      data() {
        return {
          str: '',
        }
      },
      watch: {
        str(newVal, oldVal) {
          // 在监听你使用update事件来更新word,而在父组件不需要调用该函数
          this.$emit('update:word', newVal);
        }
      }
    }
    </script>
    

    相关文章

      网友评论

          本文标题:使用.sync 来让子组件修改父组件的值

          本文链接:https://www.haomeiwen.com/subject/adtfpltx.html