programing

복제/복사 상태가 빈 상태로 반환됩니다.

minecode 2022. 8. 11. 21:34
반응형

복제/복사 상태가 빈 상태로 반환됩니다.

lodash의 cloneDeep를 사용하여 스토어에서 전달된 사용자 개체를 복제하는 데 문제가 있습니다.템플릿의 데이터를 렌더링하려고 하면{{ user }}에 스토어에서 취득한 데이터 및{{ userCopy }}에 빈 스토어를 나타냅니다.왜 이런 일이 일어나는지 모르겠어요. 저는 Vue에 처음 와봐요.

스토어/스태프/스태프/스태프/스태프

import StaffService from '~/services/StaffService.js'
export const state = () => ({
  user: {
    offers: '',
    legal: ''
  }
})
export const mutations = {
  SET_USER(state, user) {
    state.user = user
  },
}

export const actions = {

  fetchUser({ commit, getters }, id) {
    const user = getters.getUserById(id)

    if (user) {
      commit('SET_USER', user)
    } else {
      StaffService.getUser(id)
        .then((response) => {
          commit('SET_USER', response.data)
        })
        .catch((error) => {
          console.log('There was an error:', error.response)
        })
    }
  },

}

export const getters = {
  getUserById: (state) => (id) => {
    return state.staff.find((user) => user.id === id)
  }
}

페이지 / 페이지 / ID / _id . vue

<template>
  <div>
    {{ user }} // will display the whole object 
    {{ userCopy }} // will only display empty store object
  </div>
</template>

<script>
import _ from 'lodash'

data() {
  return {
    userCopy: _.cloneDeep(this.$store.state.staff.user)
  }
},
computed: {
  ...mapState({ user: (state) => state.staff.user })
},
created() {
   this.$store.dispatch('staff/fetchUser', this.$route.params.id)
},
</script>

제 생각엔 Vue 인스턴스의 경우data이 전에 초기화됩니다.state사용할 수 있게 됩니다.하는 동안에computed데이터 소스 변경에 따라 소품이 채워지거나 채워집니다.

컴포넌트의 값을 변경할 필요가 없는 경우user실행 시, 저는 이 파일을computed소유물.

컴포넌트가 런타임 중에 값을 변경하는 경우(예를 들어 실행 시)v-model'd to input(입력)'에는 두 가지 방법이 있습니다.

방법 1: 사용mounted후크

이것은, 다음의 순서에 의해서 행해집니다.userdata속성을 선택한 후 인스턴스를 마운트할 때 다음과 같이 값을 할당합니다.

mounted () {
  this.$data.userCopy = _.cloneDeep(this.$store.state.staff.user)
}

방법 2: 사용computed와 함께getter그리고.setter기능들.

보통, 당신은 그것을 바꾸면 안 됩니다.computed값입니다. 하지만 세터 기능을 사용해서 할 수 있습니다.이를 통해 Vue가 변경 시도를 감지했을 때computed그것을 실행할 것을 지지하다.set()오래된 값과 새로운 값을 인수로 지정합니다.이 함수는 소스의 값을 변경하여get()는 이를 반영하기 위해 값을 반환했습니다.예를 들어 다음과 같습니다.

computed: {
  userCopy: {
    get () {
      return _.cloneDeep(this.$store.state.staff.user)
    },
    set (newValue) {
      this.$store.commit('updateStaff', newValue) // Replace this line with your equivalent state mutator.
    }
  }
}

언급URL : https://stackoverflow.com/questions/62657355/clone-copy-state-is-returning-empty-state

반응형