VUE3
<template>
<div>{{ publicMessage }}</div>
</template>
<script setup>
import { reactive, computed } from 'vue'
const author = reactive({
name: 'zhangsan',
books: [
'books1',
'books2',
'books3'
]
})
const publicMessage = computed(() => {
return author.books.length > 0 ? 'YES' : 'NO'
})
</script>
VUE2
<body>
<div>{{ publicMessage }}</div>
</body>
<script>
export default {
data(){
author : {
name: 'zhangsan',
books: [
'books1',
'books2',
'books3'
]
}
},
methods: {},
computed: {
publicMessage () {
return author.books.length > 0 ? 'YES' : 'NO'
}
}
}
</script>
1. 计算属性特点:
1.1 计算结果不保存,data数据无改变,data中任何数据得变动,都会导致重复计算。
1.2 计算结果的改变,依赖于计算数据的变动。
1.3 计算属性默认只读,通过getter、setter修改计算属性。
注:getter中只做计算,不能更改状态、做异步请求、或者更改DOM
1.4 计算属性应该被视为只读,永远不应该被修改;即使一定要修改值,也应该去修改依赖数据源的值。
VUE3
<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
const fullName = computed({
// getter
get() {
return firstName.value + ' ' + lastName.value
},
// setter
set(newValue) {
// 注意:我们这里使用的是解构赋值语法
[firstName.value, lastName.value] = newValue.split(' ')
}
})
</script>
VUE2
<body>
<div>{{ fullName }}</div>
</body>
<script>
export default {
data(){
firstname: 'John',
lastname: 'Doe'
}
},
methods: {},
computed: {
fullName: {
get(){
return this.firstname + ' ' + this.lastname
},
set(newValue) {
const name = newValue.split(' ')
this.firstname = name[0]
this.lastname = name[name.length -1]
}
}
}
}
</script>
2. 计算属性的缺点:
2.1 增加资源消耗 —— 使用过滤器
2.2 异步无法监听 —— 添加watch监听