聲明要在組件實例上公開的計算屬性。
類型
interface ComponentOptions {
computed?: {
[key: string]: ComputedGetter<any> | WritableComputedOptions<any>
}
}
type ComputedGetter<T> = (
this: ComponentPublicInstance,
vm: ComponentPublicInstance
) => T
type ComputedSetter<T> = (
this: ComponentPublicInstance,
value: T
) => void
type WritableComputedOptions<T> = {
get: ComputedGetter<T>
set: ComputedSetter<T>
}
細節
該選項接受一個對象,其中鍵是計算屬性的名稱,值是計算 getter,或者是具有 get
和 set
方法的對象(用於可寫計算屬性)。
所有的 getter 和 setter 都有它們的 this
上下文自動綁定到組件實例。
請注意,如果您使用帶有計算屬性的箭頭函數,this
將不會指向組件的實例,但您仍然可以將實例作為函數的第一個參數來訪問:
export default {
computed: {
aDouble: (vm) => vm.a * 2
}
}
示例
export default {
data() {
return { a: 1 }
},
computed: {
// readonly
aDouble() {
return this.a * 2
},
// writable
aPlus: {
get() {
return this.a + 1
},
set(v) {
this.a = v - 1
}
}
},
created() {
console.log(this.aDouble) // => 2
console.log(this.aPlus) // => 2
this.aPlus = 3
console.log(this.a) // => 2
console.log(this.aDouble) // => 4
}
}
相關用法
- Vue.js computed()用法及代碼示例
- Vue.js components用法及代碼示例
- Vue.js customRef()用法及代碼示例
- Vue.js createRenderer()用法及代碼示例
- Vue.js createApp()用法及代碼示例
- Vue.js cloneVNode()用法及代碼示例
- Vue.js useSSRContext()用法及代碼示例
- Vue.js app.directive()用法及代碼示例
- Vue.js mergeProps()用法及代碼示例
- Vue.js app.config.warnHandler用法及代碼示例
- Vue.js pipeToWebWritable()用法及代碼示例
- Vue.js app.use()用法及代碼示例
- Vue.js v-pre用法及代碼示例
- Vue.js h()用法及代碼示例
- Vue.js serverPrefetch用法及代碼示例
- Vue.js <Transition>用法及代碼示例
- Vue.js inject()用法及代碼示例
- Vue.js mixins用法及代碼示例
- Vue.js ComponentCustomProps用法及代碼示例
- Vue.js reactive()用法及代碼示例
- Vue.js ComponentCustomProperties用法及代碼示例
- Vue.js app.mount()用法及代碼示例
- Vue.js <component>用法及代碼示例
- Vue.js onMounted()用法及代碼示例
- Vue.js app.config.errorHandler用法及代碼示例
注:本文由純淨天空篩選整理自vuejs.org大神的英文原創作品 computed。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。