【问题标题】:Vue watch of sync non-required property同步非必需属性的Vue手表
【发布时间】:2021-03-03 22:50:24
【问题描述】:

我们在 Child 组件中同步了属性并监视了这个属性。此属性设置为默认值(非必需)

如果我们不提供从父级到子级的 prop,是否有任何方法可以强制监视子组件中的属性更改?

演示:https://codesandbox.io/s/vue-watch-sync-prop-bug-demo-lofei

我从下面的两个组件中添加了一些代码。

- Parent.vue

<template>
  <!-- watch inside not works if remove ':message.sync' here -->
  <Child :message.sync="message" />
</template>

<script>
import Child from "./Child";
export default {
  name: "Parent",
  components: { Child },
  data: function (params) {
    return {
      message: "",
    };
  },
};
</script>

- Child.vue

<template>
  <div>message: {{ messageValue }}</div>
</template>

<script>
export default {
  name: "Child",
  props: {
    message: {
      type: String,
      default: "",
    },
  },
  computed: {
    messageValue: {
      get() {
        return this.message;
      },
      set(value) {
        this.$emit("update:message", value);
      },
    },
  },
  watch: {
    message(value) {
      // this not executing
    },
  },
};
</script>

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    尝试将immediate:true 添加到手表属性:

     watch: {
        message:{
          handler(value) {
         
          },
          immediate:true
        }
      },
    

    【讨论】:

    • 你缺少应该是&lt;Child :message="message"/&gt;的道具绑定
    • 这个属性不是必需的(因为我设置了默认值)。所以这就是我的问题:如果我跳过这个绑定,为什么 watch 不起作用,我怎样才能强制 watch 这个属性?
    • 但它在第一次渲染时渲染默认消息codesandbox.io/s/…
    • 哦,我的错。我刚刚明白我正在发出更新,但实际值没有改变,因为 prop 没有绑定并且它没有保存新值......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2011-03-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多