提示:首先确认数据是没问题的,此时如果是界面没有实施渲染,特别是等到用户下一次操作才渲染。以下的解决方案才有效果
出现问题的原因:
我使用了el-table,v-for渲染表单的控件,该表单中有两个下拉框,当A下拉框改变selected值时,B下拉框要去请求接口,更新下拉选项。此时把最新的下拉选项更新上去,但是我发现数据请求到了,赋值上去,但是下拉不会显示最新的,要等到再次改变A下拉框的seleted值时,B下拉框的下拉选项才显示上一次请求到的数据。
解决方案
methods: {
XXfunction() {
// ...
this.$forceUpdate();
// ...
}
}
如果您是组件不会渲染,可以考虑如下方案:
1.使用v-if
v-if指令,该指令仅在组件为true时才渲染。如果为false,则该组件在DOM中不存在。
<template>
<my-component v-if="renderComponent" />
</template>
<script>
export default {
data() {
return {
renderComponent: true,
};
},
methods: {
forceRerender() {
// 从 DOM 中删除 my-component 组件
this.renderComponent = false;
this.$nextTick(() => {
// 在 DOM 中添加 my-component 组件
this.renderComponent = true;
});
}
}
};
</script>
上面的过程大致如下:
刚开始 renderComponent设置为true,因此渲染 my-component 组件
当我们调用forceRerender时,我们立即将renderComponent设置为false
我们停止渲染my-component,因为v-if指令现在计算结果为false
在nextTick方法中将renderComponent设置回true
当v-if指令的计算结果为true时,再次渲染my-component
在这个过程中,有两个部分比较重要
首先,我们必须等到nextTick,否则我们不会看到任何变化。
在Vue中,一个 tick 是一个DOM更新周期。Vue将收集在同一 tick 中进行的所有更新,在 tick 结束时,它将根据这些更新来渲染 DOM 中的内容。如果我们不等到next tick,我们对renderComponent的更新就会自动取消,什么也不会改变。
其次,当我们第二次渲染时,Vue将创建一个全新的组件。Vue 将销毁第一个,并创建一个新的,这意味着我们的新my-component将像正常情况一样经历其所有生命周期-created,mounted等。
另外,nextTick 可以与 promise 一起使用:
forceRerender() {
// 从 DOM 中删除 my-component 组件
this.renderComponent = false;
this.$nextTick().then(() => {
this.renderComponent = true;
});
}
2.给组件加key
每次forceRerender被调用时,我们的componentKey都会改变。当这种情况发生时,Vue将知道它必须销毁组件并创建一个新组件。我们得到的是一个子组件,它将重新初始化自身并“重置”其状态。
<template>
<component-to-re-render :key="componentKey" />
</template>
export default {
data() {
return {
componentKey: 0,
};
},
methods: {
forceRerender() {
this.componentKey += 1;
}
}
}
更多组件可参考:
https://blog.csdn.net/qq449245884/article/details/104057886