【问题标题】:Detect change to modelValue in Vue 3在 Vue 3 中检测对 modelValue 的更改
【发布时间】:2021-05-21 22:38:36
【问题描述】:

有没有办法检测自定义组件中对 modelValue 的更改?我想将更改推送到所见即所得的编辑器。

我尝试观察 modelValue,但为 modelValue 发出更新触发了该观察,从而创建了循环数据流。


代码:

export default {
  props: ['modelValue'],
  watch: {
    modelValue (val) {
      this.editor.editor.loadHTML(val)
    }
  },
  mounted () {
    this.editor.editor.loadHTML(val)
    this.editor.addEventListener('trix-change', 
      (event) => this.$emit('update:modelValue', event.target.value))
  }
}

<TextEditor v-model="someHtml"></TextEditor>

【问题讨论】:

  • 你能分享一些代码吗?
  • @Daniel:添加了一些代码

标签: vuejs3


【解决方案1】:

在 VueJS v3 中,custom v-model handling changed 的事件名称为 'update:modelValue'。

您可以像这样收听这些事件:v-on:update:modelValue="handler"

对于更完整的示例,假设您有一个具有以下属性/方法的 Toggle 组件:

...
props: {
        modelValue: Boolean,
},
data() {
    return {
        toggleState: false,
    };
},
methods: {
    toggle() {
        this.toggleState = !this.toggleState;
        this.$emit('update:modelValue', this.toggleState);
    }
}
...

您可以使用该切换组件:

<Toggle v-model="someProperty" v-on:update:modelValue="myMethodForTheEvent"/>

附带说明,您还可以使用 setter 对计算属性进行 v-model;允许您在不使用 update:modelValue 事件的情况下内化您的状态更改。在此示例中,它假定您在自定义 Toggle 组件上使用 v-model="customProperty"

 computed: {
      customProperty: {
        get() {
          return this.internalProperty;
        },
        set(v) {
          this.internalProperty = v;
          console.log('This runs when the custom component 'updates' the v-model value.);
        },
      }
    },

【讨论】:

  • 感谢您的回复。我的问题可能不清楚,但我的问题是在您的示例 Toggle 中检测到组件中对 modelValue 的更改。
【解决方案2】:

我遇到了同样的问题,并通过对您调用 watch 函数的方式稍作调整来解决它:

setup(props) {
      watch(() => props.modelValue, (newValue) => {
            // do something
      })
}

因此,重要的是添加() =&gt; props.modelValue 而不是仅仅将props.modelValue 作为watch 函数的第一个参数。

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 2018-09-20
    • 2019-05-02
    • 1970-01-01
    • 2021-08-19
    • 2013-02-21
    • 2018-12-15
    • 1970-01-01
    相关资源
    最近更新 更多