source

vuex 상태를 html 입력 요소에 바인딩하지 않았는데도 구성 요소 수준 상태를 변경하면 vuex 상태가 변경되는 이유는 무엇입니까?

nicesource 2023. 1. 19. 07:05
반응형

vuex 상태를 html 입력 요소에 바인딩하지 않았는데도 구성 요소 수준 상태를 변경하면 vuex 상태가 변경되는 이유는 무엇입니까?

나는 다음과 같은 vue 스토어를 가지고 있다.

store.displaces를 설정합니다.

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 컴포넌트는 다음과 같습니다.

Supp.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
},

supplementStoreAPI에서 값을 가져오고 다음과 같은 JSON 객체입니다.

supplementStore = {
  logged: true
}

그래서 제가Supp.vue컴포넌트가 로컬 상태로 마운트되었습니다.supps될 것이다

supps = {
    logged: true
  }

supps유형 입력 필드에 바인딩되어 있습니다.(Supp.vue)사용방법v-model지시.

달성하고 싶은 것:

체크박스를 끄면supps.logged사이에서 전환해야 한다true그리고.false그렇지만,supplementStore.logged(입력필드에 바인드 되어 있지 않기 때문에)는 변경되지 않습니다.

내가 관찰한 것은Vue Devtools:

체크박스를 끄면 둘 다supps.logged그리고.supplementStore.logged양쪽이 true와 false를 동시에 토글하고 있는 반면, 이 두 가지는 true와 false를 동시에 토글하고 있습니다.supps.logged토글할 수 있습니다.

누가 나를 도와줄 수 있나요?

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
},

해보셨어요?Object.assign대신?JS에서 개체는 참조에 의해 전달됩니다.변수에 하나를 할당하면 변수가 내부에서 변경되면 원래 변수가 변경됩니다.

개체를 복제하려면 다음과 같이 하십시오.

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

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

편집: 데모에서 보듯이Vue.set또는this.$set이 기능을 하지 않습니다(실행).

API에서 받은 데이터는supplementStore는 오브젝트 배열의 형태였습니다.

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

그리고 Jacob Goh와 Yousof K.가 각각 답변에서 언급했듯이 오브젝트와 배열은 javascript에서 참조에 의해 전달된다고 나는 다음 코드를 사용하여 값을 할당하기로 결정했다.supplementStore로.supps내 안에mounted()후크:

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

  }

체크박스를 끄면supplementStore.logged이 동안 변경되지 않습니다.supps.logged내가 원하는 대로 진실과 거짓을 바꾼다.

언급URL : https://stackoverflow.com/questions/56088901/why-does-my-vuex-state-change-on-changing-my-component-level-state-even-if-i-hav

반응형