您的位置:首页 > Web前端 > Vue.js

前端学习笔记四:Vue(2)计算属性和监听属性

2020-08-04 22:47 841 查看

继续。

示例2:
代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script src="../../vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="showText">
<p>原来的字符串: {{message}}</p>
<p>计算反转后的字符串: {{comReversedMessage}}</p>
<p>函数反转后的字符串: {{funReversedMessage()}}</p>
</div>

<div id="compute">
毫米:<input type="text" v-model="millimeter"/>
微米:<input type="text" v-model="micron"/>
<p id="showSize"></p>
<p style="font-size: 20px;">计数器:{{clkCount}}</p>
<button @click="clkCount++" style="font-size: 18px;">不要点我!</button>
</div>

<script type="text/javascript">
var itemSize = new Vue({
el: '#compute',
data:{
millimeter: 0,
micron: 0,
clkCount: 1
},
methods:{
},
computed:{
},
/*
监听属性watch用来响应数据的变化。
当对象里被监听的数据改变时,watch会实时监听数据变化并根据需求改变相应的值。
*/
watch:{
millimeter: function(){
this.micron = this.millimeter / 1000;
},
micron: function(){
this.millimeter = this.micron * 1000;
}
}
});
itemSize.$watch('clkCount', function(nval, oval){
alert('你点按钮的次数由' + oval + '次变成了' + nval + '次');
});
itemSize.$watch('millimeter', function(newValue, oldValue){
document.getElementById('showSize').innerHTML = "修改前的毫米值为: " + oldValue + ",修改后的毫米值为: " + newValue;
});

var txt = new Vue({
el:'#showText',
data:{
message: "I'd rather be dry, but at least I'm alive!",
count1: 0,
count2: 0,
},
computed:{ // computed与methods类似,都可以动态当作方法来使用
// 计算属性的 getter
comReversedMessage: function(){
this.count1 += 1;
document.writeln("计算反转共被调用" + this.count1 + "次");

// this 指针指向 vm 实例
return this.message.split('').reverse().join('');
}
},
/*
computed和methods的区别有: 1. 调用的时候,methods要加上括号;
2. computed基于依赖缓存,只有相关依赖发生改变时才会重新取值;
而使用methods,在重新渲染的时候,函数总会重新调用执行。
*/
methods:{
funReversedMessage: function(){
this.count2 += 1;
document.writeln("</br>函数反转共被调用" + this.count2 + "次");

return this.message.split('').reverse().join('');
}
}
});
</script>
</body>
</html>

运行结果:
不用数了,函数反转总共被调用了102次。虽然不知道为什么有这么多次

点一下按钮后会是这样:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: