在 Vue 3 推出之前,Vue 2 只有一種寫法 —— Options API。
它的特色是:用一個物件把所有功能分區塊寫清楚。
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
},
computed: {
double() {
return this.count * 2
}
},
watch: {
count(newVal, oldVal) {
console.log(`count 從 ${oldVal} 變成 ${newVal}`)
}
}
}
以搜尋功能為例,能直接用 Options API 管理狀態與計算。
<script>
import posts from '../data/data.js'
export default {
data() {
return {
keyword: '',
posts
}
},
computed: {
filteredPosts() {
if (!this.keyword) return this.posts
return this.posts.filter(p =>
p.pSchool.includes(this.keyword) ||
p.pDep.includes(this.keyword) ||
p.pResult1.includes(this.keyword)
)
}
}
}
</script>
優點
缺點