如果在data()或setup()中声明 data,则app.component实例中的 data不是响应性的



我想在组件中声明新的reactive变量。全局设置组件(在app.component实例之外)并将其返回给data()setup()函数工作。但是当我在data()setup()事件中声明响应对象时,它不起作用。

下面是示例代码:
const editEducationData = reactive({
attainment: null,
degree: null,
yeargraduated: null
});
app.component("educationmodal", {
setup() {
// this is reactive...
return editEducationData;
// this is not reactive..
return reactive({
attainment: null,
degree: null,
yeargraduated: null
});
},
methods: {
setValues() {
// this doesen't work....
this.attainment = "value";
// this works....
editEducationData.attainment = "newvalue";
},
show() {
}
},
template: 
/* html */
`<div>{{ attainment }}</div>`
});
/* this updates {{ attainment }} in template */
editEducationData.attainment = "new values";
/* this does not update {{ attainment }} in template but setValues method is firing  */
app.component("educationmodal").methods.setValues();

editEducationData中编辑值可以工作,但在this中即使在实例内也不行(请参考上述代码中的方法)。

这个问题的可能解决方案是什么?

在同一个组件中使用组合和选项API交换数据是不好的做法,它会使你的组件不一致,建议使用一个基于响应性属性的API:

app.component("educationmodal", {
setup() {

const editEducationData = reactive({
attainment: null,
degree: null,
yeargraduated: null
});

function setValues(){
editEducationData.attainment = "newvalue";
}

return {
editEducationData,
setValues
}
},

template: 
/* html */
`<div>{{ editEducationData.attainment }}</div>`
});

相关内容

最新更新