概述
我们在做一些数据查询、多条件搜索的时候,往往会有重置按钮,这个时候往往会用到数据重置。
基础示例
这个是基础的示例,就是在点击重置的时候吧参数重新赋值。但是当字段过多时,这么使用在代码体现上就不是很友好了。
<script>
export default {
data() {
return {
formData: {
name: undefined,
sex: 1,
mobile: null,
age: undefined,
type: "",
},
};
},
methods: {
handleReset() {
this.formData= {
name: undefined,
sex: 1,
mobile: null,
age: undefined,
type: "",
};
},
},
};
</script>
VUE2中进阶的用法
vue2中我们可以使用一种依赖于选项 API 内部的解决方法$options
<script>
export default {
data() {
return {
formData: {
name: undefined,
sex: 1,
mobile: null,
age: undefined,
type: "",
},
};
},
methods: {
handleReset() {
Object.assign(this.listQuery, this.$options.data().formData);
},
},
};
</script>
VUE3中进阶的用法
vue3我们更倾向于使用组合式API,而不是使用vue2的API。在这里推荐一种可重用函数的写法,也十分实用。
可重用函数既可以用来定义初始数据,也可以用来重置数据。
<script setup>
import { reactive } from "vue";
//定义可重用函数和初始数据
const originData = () => ({ name: "", age: "" });
//赋值
const formData= reactive(originData());
formData.name = "测试";
formData.age = 18;
//数据重置
const handleReset = () => {
Object.assign(formData, originData());
};
</script>