computed的基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>计算属性实现</title>
<script src="../04-计算属性/vue.js"></script>
</head>
<body>
<div id="root">
姓:<input type="text" v-model:value="firstName">
<hr>
名:<input type="text" v-model:value="lastName">
<hr>
姓名:<span>{{fullName}}</span>
姓名:<span>{{fullName}}</span>
姓名:<span>{{fullName}}</span>
</div>
<script>
let vm = new Vue({
el: '#root',
data: {
firstName:'zhang',
lastName:'san'
},
methods: {
},
computed: {
fullName:{
// get 作用 当有人读取fullName时 get就会被调用 且返回值就作为fullName的值
// get调用时间 1.初次读取fullName时 2.所依赖的数据发生变化时
get(){
console.log('get被调用了');
return this.firstName+this.lastName
},
// set什么时候调用 当fullName被修改时
set(){
console.log();
const arr = value.split('-')
this.firstName = arr[0]
this.lastName = arr[1];
}
}
}
})
</script>
</body>
</html>
给了一个姓和名,此时想要获得他的全部名称,可以通过计算属性computed中写一个fullName方法,默认具有get方法,set方法需要手动定义
计算属性-缓存
在上面body的span中调用三次fullName方法,但是控制台中只打印一次get被调用了,说明computed具有缓存属性,且只要依赖的数据不变,就不会被再次调用。
什么叫被依赖的数据不变呢?
比如:在data中再定义一个x属性
<div id="root">
姓:<input type="text" v-model:value="firstName">
<hr>
名:<input type="text" v-model:value="lastName">
<hr>
没依赖:<input type="text" v-model:value="x">
<hr>
姓名:<span>{{fullName}}</span>
姓名:<span>{{fullName}}</span>
姓名:<span>{{fullName}}</span>
</div>
<script>
let vm = new Vue({
el: '#root',
data: {
firstName:'zhang',
lastName:'san',
x:'没被依赖吧?'
},
methods: {
},
computed: {
fullName:{
// get 作用 当有人读取fullName时 get就会被调用 且返回值就作为fullName的值
// get调用时间 1.初次读取fullName时 2.所依赖的数据发生变化时
get(){
console.log('get被调用了');
return this.firstName+this.lastName
},
// set什么时候调用 当fullName被修改时
set(){
console.log();
const arr = value.split('-')
this.firstName = arr[0]
this.lastName = arr[1];
}
}
}
})
</script>
更改x属性的值,但是fullName所依赖的数据firstName和lastName没有更改,所以get也不会重新被调用。
计算属性简写
确定只读不写时
computed: {
fullName:{
// 简写 确定只读不写
fullName(){
console.log('get被调用了');
return this.firstName+this.lastName
}
}
}