在VUE 3中重置组件反应性数据的最佳方法是什么?
假设有一个具有多个反应性数据的组件。我们如何将它们重置回初始状态?
<script setup>
const var_a = ref("");
const var_b = ref([]);
const var_c = ref({});
const var_d = ref(false);
const var_e = ref(1);
const var_f = ref("a");
...
</script>
在VUE 2中,我们可以通过仅将Object.Assign()与对象使用object.sign()来做到这一点,然后只需在需要时将其重新定义为data()。
<script>
function initialData (){
return {
var_a: "",
var_b: [],
var_c: {},
var_d: false,
var_e: 1,
var_f: "a",
}
}
export default {
data: function (){
return initialState();
},
methods:{
resetData: function (){
Object.assign(this.$data, initialData());
}
}
}
</script>
但是在VUE 3中,它不起作用。
我可以将所有组件数据声明到const state
然后循环槽,但感觉不只是一种方便的方式。
那么,将VUE 3上的这些方法重置的最佳方法是什么?
Let's say there is a component with multiple reactive data. How can we reset them back to the initial state?
<script setup>
const var_a = ref("");
const var_b = ref([]);
const var_c = ref({});
const var_d = ref(false);
const var_e = ref(1);
const var_f = ref("a");
...
</script>
In vue 2 we could do that by just using Object.assign() with an object and simply re/define it to data() whenever needed.
<script>
function initialData (){
return {
var_a: "",
var_b: [],
var_c: {},
var_d: false,
var_e: 1,
var_f: "a",
}
}
export default {
data: function (){
return initialState();
},
methods:{
resetData: function (){
Object.assign(this.$data, initialData());
}
}
}
</script>
But in vue 3 it does not work that way.
I could declare all the component data on to const state
then loop trough it but it does not feel like a convenient way.
So what would be the best way to reset those on vue 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果需要重置整个状态,则不应单独定义。相反,它被定义为反应性对象:
可以以与以前相同的方式重置:
如果需要,可以单独使用状态:
If the whole state needs to be reset, it shouldn't be defined separately. Instead, it's defined as reactive object:
It can be reset the same way as before:
The state can be used separately if needed: