복제/복사 상태가 빈 상태로 반환됩니다.
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
후크
이것은, 다음의 순서에 의해서 행해집니다.user
에data
속성을 선택한 후 인스턴스를 마운트할 때 다음과 같이 값을 할당합니다.
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
'programing' 카테고리의 다른 글
Java의 Collections.singletonList()를 사용하시겠습니까? (0) | 2022.08.11 |
---|---|
xcode 프로젝트에 포함 경로를 설정하는 방법 (0) | 2022.08.11 |
bootstrap-vue 테이블에 대한 세부 정보 표시 문제 (0) | 2022.08.11 |
타입 세이프 에넘을 작성하는 방법 (0) | 2022.08.11 |
vue.material에서의 vue.modial2 라우팅 (0) | 2022.08.11 |