11-Vue核心-计算属性 vs 监视属性
计算属性(computed) vs 监视属性(watch)
1) computed 能完成的功能,watch 都可以完成
2) watch 能完成的功能,computed 不一定能完成。例如 watch 可以进行异步操作。
两个重要的原则
1) 所有被 Vue 管理的函数,最好写成通函数,这样 this 的指向才是 vm 或 组件实例对象
2) 所有不被 Vue 所管理的函数 (定时器的回调函数、ajax 的回调函数等、Promise 的回调函数),最好写成箭头函数,这样 this 的指向才是 vm 或 组件实例对象
分别使用计算属性和监视属性,实现姓名案例

1.使用计算属性实现姓名案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性实现姓名案例</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model:value="firstname" placeholder="请输入您的姓"><br/>
名:<input type="text" v-model:value="lastname" placeholder="请输入您的名"><br/><br/>
<!--使用计算属性实现-->
姓名全称:<span>{{fullName}}</span><br/>
</div>
<script type="text/javascript">
// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false;
const vm = new Vue({
el:"#root",
data(){
return{
firstname:"任",
lastname:"先生"
}
},
// 计算属性:要用的属性不存在,需要通过已有属性计算得来
computed:{
// 计算属性的简写写法(默认没有set方法)
fullName(){
console.log("@---正在调用get()方法...")
return this.firstname + "-" + this.lastname;
}
}
})
</script>
</body>
</html>
2.使用监视属性实现姓名案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>监视属性实现姓名案例</title>
<!-- 引入Vue -->
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model:value="firstname" placeholder="请输入您的姓"><br/>
名:<input type="text" v-model:value="lastname" placeholder="请输入您的名"><br/><br/>
<!--使用计算属性实现-->
姓名全称:<span>{{fullname2}}</span><br/>
</div>
<script type="text/javascript">
// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false;
const vm = new Vue({
el:"#root",
data(){
return{
firstname:"任",
lastname:"先生",
fullname2:"任-先生"
}
},
// 监视属性:当被监视的属性发生变化时,handle()回调函数自动调用
watch:{
// 监视属性的简写写法(除了handler之外,没有其他的配置项了)
firstname(newValue,oldValue){
// this.fullname2 = newValue + "-" + this.lastname
// setTimeout定时器(异步操作),间隔一秒再实现相应操作
setTimeout(() => {return this.fullname2 = newValue + "-" + this.lastname},1000)
},
lastname(newValue,oldValue){
this.fullname2 = this.firstname + "-" + newValue
},
}
})
</script>
</body>
</html>

浙公网安备 33010602011771号