Vue2、Vue3如何清空、重置data数据
Vue2、Vue3如何清空、重置data数据
·
简单重置
直接对data中的所有数据一个个进行赋值,新手往往都会这么做,字段少时还好,但是一旦字段过多就会导致大量代码冗余,一不小心还容易输错。
<script> export default{ data() { return { robotName: "gpt机器人", chatList: [], inputMsg: "", eventSource: null, userId: "" }; }, methods: { reset() { this.robotName="gpt机器人"; this.chatList = []; this.inputMsg = ""; this.eventSource = null; this.userId = ""; }, }, }; </script>
Vue2数据重置
<script> import { reactive, toRefs } from 'vue'; export default{ data() { return { robotName: "gpt机器人", chatList: [], inputMsg: "", eventSource: null, userId: "" }; }, methods: { reset() { Object.assign(this.$data, this.$options.data.call(this)) }, }, }; </script>
可以发现我们用Object.assign(this.$data, this.$options.data.call(this))
一行代码替代了复杂的赋值操作,这句话实际就是调用了data
这个函数,并把this作为参数传人,将 data
函数中定义的初始数据合并到实例的数据中,以确保实例成功重置。
Vue3数据重置
<script> export default { setup() { const data = reactive({ robotName: "gpt机器人", chatList: [], inputMsg: "", eventSource: null, userId: "" }); const originalData = reactive({ robotName: "gpt机器人", chatList: [], inputMsg: "", eventSource: null, userId: "" }); const reset = () => { Object.assign(data, originalData); }; return { ...toRefs(data), reset }; } }; </script>
Vue3数据重置(setup语法糖)
<script setup> import { reactive } from "vue"; const originData = reactive({ robotName: "gpt机器人", chatList: [], inputMsg: "", eventSource: null, userId: "" }); const data = reactive({ robotName: "gpt机器人", chatList: [], inputMsg: "", eventSource: null, userId: "" }); const reset = () => { Object.assign(data, originData); }; </script>
更多推荐
已为社区贡献1条内容
所有评论(0)