<template>
<p>Has published books:</p>
<span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>
<span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>
<span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>
<p>methods:Has published books:</p>
<span>{{ publishedBooksMessageMethod() }}</span>
<span>{{ publishedBooksMessageMethod() }}</span>
<span>{{ publishedBooksMessageMethod() }}</span>
<button @click="publishedBooksMessageMethod">按钮事件测试</button>
<p>computed:Has published books:</p>
<span>{{ publishedBooksMessage }}</span>
<span>{{ publishedBooksMessage }}</span>
<span>{{ publishedBooksMessage }}</span>
<p>computed:date</p>
<span>{{ now }}</span>
<span>{{ now }}</span>
<span>{{ now }} </span>
<div>
<button @click="author.books.push('vue - text')">修改书单</button>
</div>
<div>
<button @click="publishedBooksMessage = 'text'">添加书单-set</button>
</div>
</template>
<script>
export default {
data() {
return {
author: {
name: 'John Doe',
books: [
'Vue 2 - Advanced Guide',
'Vue 3 - Basic Guide',
'Vue 4 - The Mystery'
]
}
}
},
// 计算属性值会基于其响应式依赖被缓存。一个计算属性仅会在其响应式依赖更新时才重新计算。
computed: {
// // 一个计算属性的 getter 简写
// publishedBooksMessage() {
// console.log('computed');
// // `this` 指向当前组件实例
// return this.author.books.length > 0 ? 'Yes' : 'No'
// },
// 完整写法
publishedBooksMessage: {
// 计算属性一般没有set方法
set: function (newValue) {
console.log(newValue);
console.log(this.author.books);
console.log(this.author.books.length)
this.author.books.push(newValue)
console.log(this.author.books);
console.log(this.author.books.length)
},
get: function () {
console.log('computed');
console.log(this.author.books.length)
return this.author.books.length > 0 ? 'Yes' : 'No'
}
},
now() {
return Date.now()
}
},
// 方法调用总是会在重渲染发生时再次执行函数
methods: {
publishedBooksMessageMethod() {
console.log('methods');
// `this` 指向当前组件实例
return this.author.books.length > 0 ? 'Yes' : 'No'
},
pushBook: function () {
console.log(this.author.books.push('test'))
console.log(this.author.books)
}
}
}
</script>
<style></style>
vue 计算属性
于 2023-05-26 11:18:14 首次发布