前言
Vue3计算、监听属性
1、计算属性
1.1、计算属性关键词: computed
<template>
<h1>{{n}} 的5倍是{{multipleN}}</h1>
</template>
<script>
export default{
name: 'SentenseTest',
data(){
return{
n : 6
}
},
computed:{
multipleN : function(){
return this.n * 5;
}
}
}
</script>
1.2、computed setter
<template>
<h1>{{firstName}} {{lastName}}</h1>
</template>
<script>
export default{
name: 'SentenseTest',
data(){
return{
firstName: "tom",
lastName: "jerry"
}
},
computed:{
fname:{
get:function(){
return this.firstName + " " + this.lastName;
},
set:function(newValue){
var names = newValue.split(" ");
this.firstName = names[0];
this.lastName = names[1];
}
}
},
mounted(){
this.fname = "Jack kara"
}
}
2、监听属性
Vue3 监听属性 watch,我们可以通过 watch 来响应数据的变化。
2.1、例子1 计数器
<template>
<h1>
<p>{{counter}}</p>
<button @click="counter++">累加</button>
</h1>
</template>
<script>
export default{
name: 'SentenseTest',
data(){
return{
counter: 1
}
},
mounted(){
this.$watch('counter', function(nval, oval) {
alert('计数器值的变化 :' + oval + ' 变为 ' + nval + '!');
});
}
}
</script>
2.2、例子2 千米与米的换算
<template>
<h1>
<p>千米:<input type="text" v-model="kilometers" @focus="currentActiveField='kilometers'"/></p>
<p>千米:<input type="text" v-model="meters" @focus="currentActiveField='meters'"/></p>
<p id = "info"></p>
</h1>
</template>
<script>
export default{
name: 'SentenseTest',
data(){
return{
meters : 0,
kilometers : 0
}
},
watch:{
kilometers : function(nVal){
if(this.currentActiveField === 'kilometers'){
this.kilometers = nVal;
this.meters = this.kilometers * 1000;
}
},
meters:function(nVal){
if(this.currentActiveField === 'meters'){
this.meters = nVal;
this.kilometers = nVal / 1000;
}
}
},
mounted(){
this.$watch('kilometers', function(nVal, oVal) {
document.getElementById("info").innerHTML = "修改前的值:" + nVal +",修改后的值:" + oVal;
});
}
}
</script>