@Watch装饰器没有激活

时间:2017-03-29 15:26:37

标签: typescript vue.js vuejs2 vue-component

我有一个简单的测试组件,模板看起来像这样:

<template>
  <div>
    <input type="text" v-model="name" class="form-control">
    <h5>{{ message }}</h5>
  </div>
</template>
<script src="./test.ts" lang="ts"></script>

组件TypeScript如下所示:

declare var Vue: typeof Function;
declare var VueClassComponent: any;

import { Component, Inject, Model, Prop, Watch } from "vue-property-decorator";

@VueClassComponent.default({
  template: require("./test.vue"),
  style: require("./test.sass"),
  props: {
    name: String,
    num: Number
  }
})
export default class TestComponent extends Vue {
  name: string;
  num: number;
  message: string = "";

  @Watch("name")
  protected onNameChanged(newName: string, oldName: string): any {
    console.log("setting " + oldName + " to " + newName);
  }

  mounted(this: any): void {
    console.log("mounted called");
    this.message = "Hello " + this.name + " " + this.num;
  }
}

当我输入input框时,@ Watch(&#34; name&#34;)处理程序永远不会触发,但我确实在console中出现了这些错误:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "name" 

input框中输入的每个字符一次。我不知道名字的设置在哪里,因为我没有把它设置在任何地方。虽然这是我的目标(更新名称),我一直在阅读,你不能直接改变价值,你需要设置@Watch处理程序,然后在其他地方设置它们(我仍然没有&#39;完全理解如何,但现在甚至无法理解。

1 个答案:

答案 0 :(得分:1)

根据我们的讨论,问题的根源在于将name声明为属性。目的是name是一个内部值,仅用于推导message。在这种情况下,手表是不必要的,计算就可以了。

declare var Vue: typeof Function;
declare var VueClassComponent: any;

import { Component, Inject, Model, Prop, Watch } from "vue-property-decorator";

@VueClassComponent.default({
  template: require("./test.vue"),
  style: require("./test.sass"),
  props: {
    num: Number
  }
})
export default class TestComponent extends Vue {
  name: string;
  num: number;

  get message(){
      return "Hello " + this.name + " " + this.num;
  }
}