循环访问Vue方法中的数据变量

Accessing data variables in Vue method for a loop

我想访问 data() 个变量


  data () {
    return {
      name: '',
      manufacturerIds: null,
      supplierIds: null,
      categoryIds: null,
      productIds: null,
      minPrice: 100,
      maxPrice: 0,
      priority: 0,
      enable: true,
      active: true,
      minMargin: 0,
      position: 0,
      isLoading: false,
      suppliers: [],
      categories: [],
      manufacturers: []
    }
  },

在同一组件的方法中。我知道我们可以将它单独称为 属性 this.someVariable 但我想要的是遍历所有变量以重置其值。因此,我没有一个一个地调用它们,而是想遍历 data() 然后为其分配一个空值(以重置)。

我已经尝试了 this.datathis.getData() 以及 this.data() 但它们都不起作用。

如果您将数据方法中的所有属性组成一个数组会怎样? 示例:

data() {
  name: '',
  manufacturerIds: null,
  supplierIds: null
  dataArray: [name, manufacturerIds, supplierIds]

}

然后调用循环遍历 dataArray 的方法?

一个一个地重置属性是个坏主意,因为您需要检查每个属性以确定需要将其设置为什么值(空值、数组、布尔值等)。您真的要 if 检查所有属性吗?

更好的方法是在对对象进行任何更改之前克隆对象,然后立即重置所有属性:

方法一:本地存储重置数据

data () {
  return {
    // Add a property for storing unchanged data
    defaultData: {},
    
    data: {}
    name: '',
    manufacturerIds: null,
    supplierIds: null,
    categoryIds: null,
    productIds: null,
    minPrice: 100,
    maxPrice: 0,
    priority: 0,
    enable: true,
    active: true,
    minMargin: 0,
    position: 0,
    isLoading: false,
    suppliers: [],
    categories: [],
    manufacturers: []
  }
},
created: {
  // Clone data before you make any changes
  this.cloneData()
},
methods: {
  cloneData () {
    // Method 1 (better way, but requires lodash module)
    const clonedData = lodash.cloneDeep(this.$data)
    // Method 2 (bad choice for complex objects, google "deep clone JS" to learn why)
    const clonedData = JSON.parse(JSON.stringify(this.$data))
    // Store the cloned data
    this.defaultData = clonedData
  },
  resetData () {
    // Reset the values using cloned data
    this.$data = this.defaultData
  }
}

方法二:在Vuex store中存储重置数据

data () {
  return {
    name: '',
    manufacturerIds: null,
    supplierIds: null,
    categoryIds: null,
    productIds: null,
    minPrice: 100,
    maxPrice: 0,
    priority: 0,
    enable: true,
    active: true,
    minMargin: 0,
    position: 0,
    isLoading: false,
    suppliers: [],
    categories: [],
    manufacturers: []
  }
},
created: {
  // Clone data before you make any changes
  this.cloneData()
},
methods: {
  cloneData () {
    // Method 1 (better way, but requires lodash module)
    const clonedData = lodash.cloneDeep(this.$data)
    // Method 2 (bad choice for complex objects, google "deep clone JS" to learn why)
    const clonedData = JSON.parse(JSON.stringify(this.$data))
    // Set the cloned data object to Vuex store
    this.$store.commit('SET_DEFAULT_DATA ', clonedData)
  },
  resetData () {
    // Reset the values using cloned data
    this.$data = this.$store.state.defaultData
  }
}

store.js

state: {
  defaultData: {}
},
mutations: {
  SET_DEFAULT_DATA (state, value) {
    state.defaultData = value
  }
}