最近在学习使用ts语法编写公司项目,昨天用到wach的时候,发现网上并没有关于if判断的一些总结,于是我认真想了想并总结出来了使用方法,欢迎指正补充.
1.首先需要从vue-property-decorator中引入Watch(大写W,注意引入空格);
2.要使用@Watch监听变化的值.
自定义一个事件来监听值的变化,并添加对应的if事件
@Watch('count')
getCount(newVal,oldVal){
//if判断语句
}
以下是自己写的demo和效果图,大家可以尝试使用一下.
<template>
<div class="home">
<p>{{count}}</p>
<p>{{text}}</p>
<button @click="addCount">点击count值增加</button>
</div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
@Component({
components: {},
})
export default class Home extends Vue {
public count: number = 1;
public text: string = "我是数字1";
public addCount() {
this.count++;
}
// watch
@Watch("count")
getCount(newVal: number) {
if (newVal == 2) {
this.text = "我是数字2";
} else if (newVal == 3) {
this.text = "我是数字3";
} else {
this.text = "我会继续增长";
}
}
}
</script>
谢谢观赏,期待您的关注!