Vuex 상태 어레이가 변환될 때 프록시 개체 전환
저는 데이터베이스에서 데이터를 가져오는 프로젝트를 개발합니다.상태 관리를 위해 Vuex를 사용합니다.
Vuex 스토어 파일
const store = createStore({
state: {
notUser: {
name: "",
email: '',
password: ''
},
user: {
name: '',
email: '',
messages: [],
about: '',
place: '',
age: '',
role: '',
blocked: false
},
problem: {
title: '',
content: ''
},
problems: [],
errorMessage: {
error: false,
message: '',
success: false
},
},
mutations: {
errorHandler(state, error) {
state.errorMessage.error = true
state.errorMessage.message = error.response.data.message
},
defineUser(state, req) {
state.user = req.data.user
console.log(state.user)
},
getProblems(state, problems) {
state.problems = problems
console.log(state.problems)
}
},
actions: {
register({ commit }, notUser) {
axios({
method: 'post',
url: 'http://localhost:3000/api/auth/register',
data: notUser,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
this.state.errorMessage.success = true
console.log(res.data.data.user)
})
.catch(err => {
this.state.errorMessage.success = false
console.log(err.response)
commit('errorHandler', err)
})
},
userLogin({commit}, notUser) {
axios({
method: 'post',
url: 'http://localhost:3000/api/auth/login',
data: notUser,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
this.state.user = res.data.data.user
this.state.errorMessage.success = true
console.log(this.state.user)
})
.catch(err => {
this.state.errorMessage.success = false
console.log(err.response)
commit('errorHandler', err)
})
},
checkUser({commit}, access_token) {
axios({
method: 'post',
url: 'http://localhost:3000/api/auth/VpW02cG0W2vGeGXs8DdLIq3dQ62qMd0',
data: access_token,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
console.log(res)
commit('defineUser', res)
return true
})
.catch(err => {
console.log(err.response)
commit('errorHandler', err)
return false
})
},
sendProblem({commit}, problem) {
axios({
method: 'post',
url: 'http://localhost:3000/api/problem/add',
data: problem,
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
console.log(res)
return true
})
.catch(err => {
console.log(err.response)
commit('errorHandler', err)
return false
})
},
getAllProblems({commit}) {
axios({
method: 'get',
url: 'http://localhost:3000/api/problem/getall',
withCredentials: true,
headers: {
"Accept": "application/json"
}
})
.then(res => {
commit('getProblems', res.data.data)
return true
})
.catch(err => {
console.log(err.response)
commit('errorHandler', err)
return false
})
}
// registerUser({commit}, user) {
// commit('register', user)
// }
},
Vue 컴포넌트:Vuex 스토어가 사용되는 위치
computed: {
...mapState(["user", 'problems'])
},
mounted() {
return this.getAll()
},
methods: {
...mapActions(['getAllProblems']),
goToAdd() {
this.$router.push('/add')
},
async getAll() {
this.getAllProblems()
}
}
문제는 getAllProblems 액션을 사용하여 요구하려고 하면 getProblems()에서 변수인 문제를 변환해야 한다는 것입니다.사실 그렇습니다.그러나 문제 변수가 변경된 후에는 프록시 개체가 됩니다.이미지는 다음과 같습니다.
프록시 오브젝트의 이미지를 다음에 나타냅니다.
@Hasan Hasanova의 코멘트 감사합니다.알겠습니다.웹사이트가 탑재되기 전에 api를 호출하여 스토어에서 변수를 가져오는 기능을 사용하였습니다.v-for 구문을 잘못 사용하여 다른 문제가 발생했습니다.코드는 다음과 같습니다.
computed: {
allProblems() { // this is the problems array that i was trying to get
return this.$store.state.allProblems
},
loader() {
return this.allProblems == null ? true : false
}
},
beforeMount() {
this.$store.dispatch('getAllProblems', {root: true})
},
템플릿 코드는 다음과 같습니다.
<div v-if="allProblems.length > 0" class="middle-side">
<div v-for="(problem) in allProblems" :key="problem.id" class="card">
<router-link :to="{ name: 'ProblemDetail', params: { id: problem._id, slug: problem.slug }}">
<div class="card-header">
<div class="card-header-title">
<div class="user-image">
<img src="../../assets/problem.png" />
</div>
<span class="user-name">{{ problem.user.name }}</span>
</div>
...
모두 감사합니다.
당신과 같은 문제가 있습니다만, 우선 getter가 돌아오기 전에 변환하고, string으로 변환하고, string을 다시 JSON으로 변환한 후 반송하는 것으로 해결했습니다.
const str = JSON.stringify(data)
return JSON.parse(str)
사용하고 싶다mapActions
행동을 촉구합니다.그런 다음 함수를 반환하는 대신 상태를 통해 데이터를 가져옵니다. 이 동작은 다음을 통해 변환을 호출합니다.commit
.
computed: {
// you have access to `problems` in the template. Use `v-if` before you `v-for` over the array of problems.
...mapState(["user", 'problems'])
},
mounted() {
this.getAllProblems();
},
methods: {
// ...mapActions(['getAllProblems']),
goToAdd() {
this.$router.push('/add')
}
}
어떤 이유로 res.data.data를 돌연변이로 전달하는 동안 발생합니다.따라서 단일 행 결과 세트를 예상하는 경우 다음과 같이 해야 합니다.
POPULATE_THIS_STATE_VAR(state, data) {
state.thisStateVar = data[0]
}
...또한 현재와 같은 결과 세트에 대한 객체 배열을 예상하는 경우 다음과 같은 작업을 수행할 수 있습니다.
POPULATE_THIS_STATE_VAR(state, data) {
if (data) {
for (let i = 0; i < data.length; i++) {
state.thisStateVar .push(data[i])
}
}
}
언급URL : https://stackoverflow.com/questions/64753224/vuex-state-array-turning-an-proxy-object-when-it-is-mutated
'programing' 카테고리의 다른 글
Python Panda - 두 데이터 프레임 간의 차이점 찾기 (0) | 2023.01.30 |
---|---|
Django 템플릿 변수가 있는 사전 값 검색 방법 (0) | 2023.01.30 |
JavaScript를 사용하여 페이지를 새로 고치려면 어떻게 해야 합니까? (0) | 2023.01.30 |
MySQL 8 DB에 연결하려면 RMySQL 또는 RMariaDB를 선택하십시오. (0) | 2023.01.30 |
python 쉘에서 화살표 키를 누르면 이스케이프 문자가 표시됩니다. (0) | 2023.01.30 |