這是一個系列文章 之前的系列文章地址:https://blog.csdn.net/www_share8/category_9877844.html
今天 我們來學習一下計算屬性 和watch
vue中關於計算屬性 就是當a,b(關聯着a),當a改變後 b也要跟着改變 這個時候就可以使用計算屬性了,watch 也有這樣的功能,watch和計算屬性的 區別 大家可以網上查詢一下資料,這不是本次的重點 。
先來看一下 vue中是如下寫計算屬性的和watch
<template>
<div class="tt">
<el-input v-model="msg"></el-input>
<div><span>我是計算屬性內容,在輸入後面添加hell--</span>{{inputContent}}</div>
<div><span>我是watch 在輸入內容後 加 world--</span>{{inputWatch}}</div>
</div>
</template>
<script>
export default {
name: 'tt',
data () {
return {
msg:'',
inputWatch: ''
}
},
computed: {
inputContent: function () {
return this.msg + ' hello'
}
},
watch: {
msg: {
handler (newData, oldData) {
this.inputWatch = newData + ' world'
},
immediate: true
}
}
}
</script>
ts 計算屬性(get 計算屬性名,引用和之前的一樣)
在來看一下 typeScript中 由於vue教程中提到了,計算屬性默認只有 getter,不過在需要時你也可以提供一個 setter:
說明計算屬性是直接可以使用 get set 來設置了 這就是下面的這樣的ts代碼了
<template>
<div class="hello">
<el-input v-model="msg"></el-input>
<div><span>我是計算屬性內容,在輸入後面添加hell--</span>{{inputContent}}</div>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
@Component
export default class HelloWorld extends Vue {
private msg: string = "測試";
get inputContent() {
return this.msg + " hello";
}
}
</script>
ts 中watch 代碼如下
首先 從vue-property-decorator引入watch,
@Watch('監聽內容',{是否需要深度監聽的內容}) 後面跟一個回調函數 名字(叫什麼都可以)
<template>
<div class="hello">
<el-input v-model="msg"></el-input>
<div><span>我是watch 在輸入內容後 加 world--</span>{{inputWatch}}</div>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
@Component
export default class HelloWorld extends Vue {
private msg: string = "測試";
private inputWatch: string = "";
@Watch("msg",{immediate: true, deep: true})
onChangeValue(newVal: string, oldVal: string) {
this.inputWatch = newVal + " world";
}
}
</script>
總結一下,對比vue 計算屬性變成了get 其他都沒有變,watch 全新的寫法 需要學習多練習