1.知识点
侦听器(watch
):
- 监听本实例中(在同一个Vue内)的变量,当然这个变量还得写在watch里
- 当监听的变量发生变化时,执行函数
- 通常只监听一个变量(异步场景)
watch
只能监听watch
里面的值的变化
计算属性(computed
):
computed
可以监听很多个变量,这些变量最好是本vue实例里面的变量(数据联动)computed
里面的任何变量发生变化,都会触发重新运算,前提是变量都是本实例内的变量
2.watch
<script type="text/javascript">
var test = 'test'
var app = new Vue({
el: '#app',
data: {
msg: 'hello Vue',
another: 'another'
},
watch: {
msg: function(newval,oldval){
console.log('newval is:'+newval);
console.log('oldval is:'+oldval);
}
},
computed: {
msg1: function(){
return 'computed:' + this.msg + ',' + this.another + test
}
}
})
</script>
watch的用法是,当监听的变量发生变化时,执行函数。 本例中这个变量是msg
。
如下图,在浏览器中改变msg的值,watch
监听到值发生了变化,会执行函数。
watch
通常只监听一个变量
watch
只能监听本实例中的变量,如下图改变 实例外 的变量 test,watch监听不到,当然函数也不会执行。
<script type="text/javascript">
var test = 'test'
var app = new Vue({
el: '#app',
data: {
msg: 'hello Vue',
another: 'another'
},
watch: {
test: function(newval,oldval){
console.log('newval is:'+newval);
console.log('oldval is:'+oldval);
}
},
computed: {
msg1: function(){
return 'computed:' + this.msg + ',' + this.another + test
}
}
})
</script>
如下图改变实例外 的变量 test,watch
监听不到,当然函数也不会执行。
3.computed
computed
可以监听很多个变量,这些变量最好是本vue实例里面的变量,数据联动
computed
里面的任何变量发生变化,都会触发重新运算,前提是变量都是本实例内的变量
初始显示:
改变another
的值之后,computed
的返回值也跟着变了
4.完整代码
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div{
color:red;
}
</style>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>{{msg}}</p>
<p>{{msg1}}</p>
</div>
<script type="text/javascript">
var test = 'test'
var app = new Vue({
el: '#app',
data: {
msg: 'hello Vue',
another: 'another'
},
watch: {
msg: function(newval,oldval){
console.log('newval is:'+newval);
console.log('oldval is:'+oldval);
}
},
computed: {
msg1: function(){
return 'computed:' + this.msg + ',' + this.another
}
}
})
</script>
</body>
</html>
注意这里引用本实例内的变量,要用 this.msg
、 this.another
展示效果