programing

상태 Vuex/Vue/Nuxt에서 새 속성 개체를 추가하는 방법

prostudy 2022. 4. 10. 21:22
반응형

상태 Vuex/Vue/Nuxt에서 새 속성 개체를 추가하는 방법

나는 주가 있고, 나는 새로운 재산을 넣고 싶다.foo: 'bar'detail

export const state = () => ({
  detail: {a: 'b', c: 'd'}
})

export const mutations = {
  SET (state, data) {
    state.detail.foo = 'bar'
  }
}

그리고 나는 html로 상태를 보여준다.

<template>
  <div>{{ data}}</div>
  /* {a: 'b', c: 'd'} */
</template>
<script>
..
  computed: {
    ...mapState({
      data: state => state.detail
    })
  },
..
</script>

자료가 보이고 있다.{a: 'b', c: 'd'}, 그러나 추가할 버튼을 클릭할 때foo: 'bar'상태가 변경되지만 html에서는 새로 고쳐지지 않는다. imush F5(브라우저 새로 고침)는 새 데이터를 표시하도록 한다.foo: 'bar'

스토어 코드에 vue 가져오기 후 사용Vue.set(state.detail,"foo" , 'bar')

import Vue from 'vue'
....

export const mutations = {
  SET (state, data) {
   Vue.set(state.detail,"foo" , 'bar')
  }
}

게이터를 사용하면 변경 사항을 다시 렌더링할 수 있음

export const state = () => ({
  detail: {a: 'b', c: 'd'}
})

export const mutations = {
  SET (state, data) {
    state.detail.foo = 'bar'
  }
}

export const getters = {
   detail: (state) => state.detail 
}

그리고 당신의 템플릿에

<template>
  <div>{{ data}}</div>
  /* {a: 'b', c: 'd'} */
</template>
<script>
..
  computed: {
    ...mapGetters({
      data: "detail"
    })
  },
..
</script>

그것을 정확하게 수입하는 것을 잊지 마라.

import { mapGetters } from "vuex"

참조URL: https://stackoverflow.com/questions/63988943/how-to-add-new-property-object-in-state-vuex-vue-nuxt

반응형