Vue.js中如何正确初始化数据?onChangeDistrict时如何重新初始化initTableFiltered
解决方法
首先,我们来梳理并解决你的问题:要让onChangeDistrict触发时,data只保留initTableFiltered加载的内容(初始状态为空数组),需要处理数据重置和代码里的小错误,具体如下:
1. 修正代码里的语法&拼写错误
你现有代码存在两处小问题,先修正它们:
initTableFiltered方法的then回调缺少闭合括号)onChangeDistrict里调用的方法名写错了,应该是initTableFiltered(注意大写的F)- 另外
methods的定义语法有误,应该是methods:而非methods()
2. 重置数据避免旧内容残留
要实现触发事件后仅使用initTableFiltered的数据,核心是在加载新数据前清空this.data,确保旧数据(来自initTableData的内容)不会和新数据叠加。
修改后的完整代码
data () { return { data: [] } }, created () { this.initTableData() }, methods: { initTableData () { db.collection('example').orderBy('owner_name', 'asc').get().then(res => { // 初始化主数据时也清空,避免重复调用时数据叠加 this.data = [] res.forEach((doc) => { this.data.push({ id: doc.id }) }) }) }, initTableFiltered () { // 先清空现有数据,确保只保留当前加载的过滤后数据 this.data = [] db.collection('filter').orderBy('name', 'asc').get().then(res => { res.forEach((doc) => { this.data.push({ id: doc.id }) }) }) }, onChangeDistrict () { this.initTableFiltered() } }
额外说明
如果你想要的是触发onChangeDistrict时,data直接变成空数组(不需要加载filter集合的数据),那简化onChangeDistrict即可:
onChangeDistrict () { this.data = [] }
内容的提问来源于stack exchange,提问作者user13708835
相关产品推荐
相关产品推荐

