“Vue 计算属性”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) |
Jihongchang(讨论 | 贡献) |
||
第36行: | 第36行: | ||
//get 什么时候调用? | //get 什么时候调用? | ||
//1.初次读取fullName时。 | //1.初次读取fullName时。 | ||
− | //2. | + | //2.所依赖的数据发生变化时,比如程序中赋值或者控制台赋值 |
get(){ | get(){ | ||
console.log('get 被调用了'); | console.log('get 被调用了'); | ||
return this.firstName + '-' + this.lastName; | return this.firstName + '-' + this.lastName; | ||
+ | }, | ||
+ | //set什么时候调用?当 fullName 被修改时。 | ||
+ | // | ||
+ | set(value){ | ||
+ | console.log('set', value); | ||
+ | const arr = value.split('-'); | ||
+ | this.firstName = arr[0]; | ||
+ | this.lastName = arr[1]; | ||
} | } | ||
} | } |
2024年8月11日 (日) 09:10的最新版本
https://www.bilibili.com/video/BV1Zy4y1K7SH?p=19
姓名案例_计算属性实现
<!DOCTYPE html>
<html lang="zh-CN">
<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" name="" id="" v-model="firstName"><br>
名:<input type="text" name="" id="" v-model="lastName"><br>
<!-- 区别于 methods 实现的优点在于:有缓存,多次通过插值表达式调用 fullName 的 getter 时,只需要调用一次 -->
全名:<span>{{fullName}}</span><br>
全名:<span>{{fullName}}</span><br>
全名:<span>{{fullName}}</span><br>
全名:<span>{{fullName}}</span><br>
全名:<span>{{fullName}}</span><br>
</div>
</body>
<script type="text/javascript">
new Vue({
el:'#root',
data:{
firstName:'张',
lastName:'三'
},
computed:{
fullName:{
//get有什么作用?当有人读取 fullName 时,get就会被调用,且返回值就作为 fullName 的值
//get 什么时候调用?
//1.初次读取fullName时。
//2.所依赖的数据发生变化时,比如程序中赋值或者控制台赋值
get(){
console.log('get 被调用了');
return this.firstName + '-' + this.lastName;
},
//set什么时候调用?当 fullName 被修改时。
//
set(value){
console.log('set', value);
const arr = value.split('-');
this.firstName = arr[0];
this.lastName = arr[1];
}
}
}
})
</script>
</html>