您可以根据本文动态添加计算属性,
Generating computed properties on the fly
.
由于属性名源是嵌套的并且(可能)是异步的,所以需要一个深度观察程序来处理更改。
属性的使用受到限制,不能在创建时编译的sfc模板上使用它。在方法中使用它时,可能需要根据调用序列检查它是否存在。
computed: {
element() {
return this.getElements(...);
},
},
watch: {
element: {
handler: function (newValue) {
if (newValue.inputName) {
this.addProp(['element', 'inputName'], () => { return 'someValue' })
}
},
deep: true
}
},
methods: {
addProp (path, getter) {
// Get property reference or undefined if not (yet) valid
const propName = path.reduce((acc, prop) => acc ? acc[prop] : undefined, this)
if (!propName) { return }
const computedProp = {
get() {
return getter()
}
}
this[propName] = computedProp
},
}