网站做优化效果怎样,做一般的网站要多久,外贸网站建设ppt模板,百度关键词搜索次数30. Vue计算属性Computed
1. 定义
Computed属性是Vue中的一个计算属性#xff0c;是一种基于其它属性值计算而来的属性值#xff0c;具有缓存机制#xff0c;在依赖的属性值发生变化时会重新计算。
使用computed属性可以避免在模板中书写过多的计算逻辑#xff0c;提高代…30. Vue计算属性Computed
1. 定义
Computed属性是Vue中的一个计算属性是一种基于其它属性值计算而来的属性值具有缓存机制在依赖的属性值发生变化时会重新计算。
使用computed属性可以避免在模板中书写过多的计算逻辑提高代码可读性和维护性。
下面是一个计算属性的示例
templatedivh3单价 {{ price }}/h3input typetext v-modelcount placeholder请输入数量个h3总价 {{ totalPrice }}/h3/div
/template
!-- vue2 --
script
export default {data() {return {price: 12,count: null}},computed: {totalPrice() {return this.price * this.count}}
}
/script
!-- vue3 --
script setup
import { ref, computed } from vue
const price ref(12)
const count ref(0)
const totalPrice computed(() {return price.value * count.value
})
/script2. computed和methods对比
计算属性是有缓存的, 当我们多次使用计算属性时, 计算属性中的运算只会执行一次。如下图
templatedivdiv{{ fullName }}/divdiv{{ fullName }}/divdiv{{ fullName }}/divdiv{{ fullName }}/divdiv{{ fullName }}/divdiv{{ fullName }}/divdiv{{ getFullName() }}/divdiv{{ getFullName() }}/divdiv{{ getFullName() }}/divdiv{{ getFullName() }}/divdiv{{ getFullName() }}/div/div
/template
!-- vue2 --
script
export default {data() {return {firstName: Jack,lastName: Ma}},computed: {fullName() {console.log(computed获取fullname);return this.firstName this.lastName;}},methods:{getFullName() {console.log(methods获取fullname);return this.firstName * this.lastName;}}
}
/script
!-- vue3 --
script setup
import { ref, computed } from vueconst firstName ref(J.K.)
const lastName ref(Rowling)const fullName computed(() {console.log(computed获取full);return firstName.value lastName.value
})const getFullName function() {console.log(methods获取full);return firstName.value lastName.value
}
/script3. Getter和Setter
计算属性默认是只读的也就是只用到getter。当你尝试修改一个计算属性时你会收到一个运行时警告。只在某些特殊场景中你可能才需要用到“可写”的属性你可以通过同时提供 getter 和 setter 来创建
!-- vue2 --
script
export default {data() {return {firstName: Jack,lastName: Ma}},computed: {fullName: {// getterget() {return this.firstName this.lastName;},// setterset(newValue) {// 注意我们这里使用的是解构赋值语法[this.firstName, this.lastName] newValue.split( )}}}, methods:{setNewName(){//设置值触发setterthis.fullName Tom Maoconsole.log(this.firstName, this.lastName);}}
}
/script
!-- vue3 --
script setup
import { ref, computed } from vueconst firstName ref(J.K.)
const lastName ref(Rowling)const fullName computed({get() {return firstName.value lastName.value},set(newValue) {[firstName.value, lastName.value] newValue.split( )}
})const setNewName function() {fullName.value John Doe
}
/script4. Getter 不应有副作用
需要注意的是computed属性必须返回一个值不能有副作用如修改数据或触发异步操作等。如果需要有副作用的计算可以使用watch属性。