Vue@Watch不会触发布尔值更改



我正在尝试在vue-ts中使用watch函数。我设置了一个监视函数,每当布尔变量值发生变化时就会触发,它根本不着火,我不知道为什么。

我的代码:

这是数据申报

<script lang="ts">
import { Vue, Component, Prop, Watch } from "vue-property-decorator";
import { CSSModule } from "@/Services/Modules/CSSModule";
@Component({})
export default class CommentCard extends Vue {
@Prop() comment!: Object;
@Prop() cmEditor!: Object;
@Prop() nextCommentDistance!: number;
@Prop({ default: 300 }) width!: number;
@Prop() commentIndex!: number;
private initialHeight: string;
private textMarker: Object;
private cssModule: Object;
private isFocused: boolean;

在挂载时,我正在更改数据值,所以手表应该触发

mounted() {
this.setDivHeight();
this.isFocused = false;
}

这是的功能

@Watch("isFocused")
highlightComment() {
if (this.textMarker) {
this.textMarker.clear();
}
const css = this.isFocused
? "background-color: " +
this.cssModule.hexToRgba(this.comment.typeColor, 0.5)
: "background-color: " +
this.cssModule.hexToRgba(this.comment.typeColor, 0.8) +
"; box-shadow: 5px 5px 4px rgb(23,24,26)";
let locations = this.comment.serialize.replace("N", "");
locations = locations.split(",");
let startLocation = locations[0].split(":");
let endLocation = locations[1].split(":");
this.textMarker = this.cmEditor.markText(
{ line: parseInt(startLocation[0]), ch: parseInt(startLocation[1]) },
{ line: parseInt(endLocation[0]), ch: parseInt(endLocation[1]) },
{
css: css,
}
);
}

它根本不会被调用,我甚至在安装后用按钮更改isFocused的值,但它仍然会启动手表。

谢谢。

您必须初始化您的属性,使它们成为反应性的。

代替:

private isFocused: boolean;

使用

private isFocused: boolean = false;

您应该为Vue应用程序中的每个属性执行此操作。请注意,您可以使用null;只要属性不是undefined,它就会工作。

有关更多信息,请参阅:https://v2.vuejs.org/v2/guide/reactivity.html

最新更新