ts(typescript)中watch及其if判断的使用总结

最近在学习使用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>

 

谢谢观赏,期待您的关注!

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值