vue侦听器和计算属性
作者:互联网
侦听器
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<p>{{ msg }}</p>
<p>{{ age }}</p>
<button @click="clickHandler">修改</button>
</div>
<script src="./vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return {
msg:"alex",
age:30
}
},
methods:{
clickHandler(){
this.msg = "wusir";
this.age = 40;
}
},
// 侦听器
watch:{
// watch监听单个属性, 如果想监听多个属性 声明多个属性的监听
// 真挺属性msg, 只要msg属性值被修改, 就会执行侦听器函数
'msg':function(value){
// value是修改的值wusir
console.log(value);
if (value == 'wusir'){
this.msg = "大无赦";
}
},
'age': function(value){
// value是修改的值age
console.log(value);
if (value == 40){
this.age = 50;
}
}
}
})
</script>
</body>
</html>
计算属性
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<p>{{ myMsg }}</p>
<button @click="clickHandler">修改</button>
</div>
<script src="./vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return {
msg:"alex",
age:30
}
},
methods:{
clickHandler(){
this.msg = "wusir";
this.age = 40;
}
},
computed:{
myMsg:function(){
// 业务逻辑
// 最后返回想要的值就行
// 计算属性默认只有getter方法
return `我的名字叫${this.msg}, 年龄是${this.age}`;
}
}
})
</script>
</body>
</html>
标签:vue,age,value,侦听器,wusir,msg,属性 来源: https://blog.csdn.net/zsx1314lovezyf/article/details/95775942