1

我有一个 Vue 商店,其中包含以下内容

store.js

import Vue from 'vue'
import Vuex from 'vuex'

const state = {
      supplementStore: {}
    }

const actions = {
  getDataFromApi ({dispatch, commit}) {
    APIrunning.then(response => {
      commit('SET_SUPPLEMENT', response)
    })
  }
}

const mutations = {
  SET_SUPPLEMENT (state, data) {
    state.supplementStore= data
  }
}

const foodstore = {
  namespaced: true,
  state,
  actions,
  mutations
}

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    foodstore
  }
})

我的 vue 组件看起来像这样

支持vue

<template>
    <input type="checkbox" v-model="supps.logged">
</template>

<script>
import {mapState, mapActions} from 'vuex'
import store from './store'

export default {
  data () {
    return {
      supps: []
    }
  },
  mounted () {
    this.supps = this.supplementStore
  },
  computed: {
    ...mapState('foodstore', ['supplementStore'])
  }
}
</script>

如您所见,我有一个名为的组件级别状态supps,一旦它被分配了supplementStore(这是一个 vuex 状态)的值mounted

mounted () {
  this.supps = this.supplementStore
},

supplementStore从 API 获取它的值,它是一个 JSON 对象,看起来像这样

supplementStore = {
  logged: true
}

因此,当我的Supp.vue组件被挂载时,我的本地状态supps将变为

supps = {
    logged: true
  }

supps(Supp.vue)使用v-model指令绑定到复选框类型的输入字段。

我想要达到的目标:

当我切换复选框时,supps.logged应该在和之间切换truefalse但是supplementStore.logged应该保持不变(因为我没有将它绑定到我的输入字段)。

我在我的观察Vue Devtools

当我切换复选框时,两个supps.loggedANDsupplementStore.logged都在同步切换,即它们都在 true 和 false 之间同步切换,而我只想supps.logged切换。

谁能帮我?

4

3 回答 3

2

在 Javascript 中,对象是通过引用传递的。(这是一个相当好的解释=> https://medium.com/nodesimplified/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c

为避免此问题,您可以在分配给 时克隆对象supps

mounted () {
  this.supps = { ...this.supplementStore } // cloning the object using Javascript Spread syntax
},
于 2019-05-11T09:23:56.923 回答
1

你试过Object.assign吗?在 JS 中,对象是通过引用传递的。如果变量内部发生变化,将 1 分配给变量将导致原始变量发生变化。

要克隆一个对象,你可以试试这个:

// this.assignedObj = new object. 
// this.obj = original object.
this.assignedObj = Object.assign({}, this.obj);

JSFiddle:https ://jsfiddle.net/mr7x4yn0/

编辑:正如您从演示中看到的那样,Vue.set或者this.$set对您不起作用(可能)。

于 2019-05-11T10:34:36.167 回答
0

The data I was receiving from the API into supplementStore was in the form of an array of objects:

supplementStore =  [
    {
        "logged": true
    },
    {
        "logged": false
    }
]

And as Jacob Goh and Yousof K. mentioned in their respective answers that objects and arrays get passed by reference in javascript, I decided to use the following code to assign the value of supplementStore to supps inside my mounted() hook:

mounted () {
    let arr = []
      for (let i = 0; i < this.supplementStore.length; i++) {
        let obj = Object.assign({}, this.supplementStore[i])
        arr.push(obj)
      }
      this.supps = arr

  }

Now when I toggle my checkbox, supplementStore.logged remains unchanged while supps.logged toggles between true and false just the way I wanted.

于 2019-05-11T11:51:58.837 回答