vuex 저장소가 변경될 때 프로펠러 속성 업데이트
vuex 저장소에 대한 돌연변이 성공 후(state.posts.post.comments
이 코드 사용 및 사용Vue.set
Vue가 개체 속성의 추가를 인식할 수 있도록:
저장/보관소/우편물.js
const mutations = {
[types.SET_POST_COMMENTS] (state, { comments, id }) {
let post = state.posts.find(post => post._id === id)
Vue.set(post, 'comments', comments)
}
}
템플릿 또는 구성 요소에 대한 업데이트가 없다.소품post
비활성 상태임(감시자도 트리거되지 않기 때문에 그럴 것임)다시 확인해보니 각 게시물의 댓글 속성에 대한 Vuex 스토어가 댓글 객체로 업데이트되고 있지만, 구성 요소SinglePost.vue
이런 변화를 보지 못했어
싱글포스트.부에를 하다
export default {
name: 'single-post',
props: {
'post': {
type: Object
}
},
data () {
return {
currPost: this.post // tried to reassign post locally
}
},
computed: {
comments() {
return this.post.comments // tried to compute comments locally
}
},
watch: {
post: function(val) { // tried to watch currPost for changes
console.log('never triggered')
this.currPost = val
}
}
궁극적으로 스토어의 코멘트를 컴포넌트 메서드에 명시적으로 반환하고 로컬 코멘트 객체를 설정하기만 하면 로컬 바(var)를 설정할 수 있지만, 중앙 스토어를 사용하고 싶다(그리고 방법이 있을 것이라고 가정함).
SinglePost 템플릿
{{comments}} // always empty
{{post}} // doesn't reflect store Vue.set for post.comments
{{currPost}} // doesn't reflect store Vue.set for post.comments
편집
내가 게시물을 받는 방법은:
getPosts ({ commit, state, getters, dispatch, rootState }, ctx) {
//other stuff
APIHelper.post('/post/search', mergedPayload).then(res => {
var results = res.data.results
commit('SET_POSTS', posts || [])
// where SET_POSTS is just state.posts = posts
화약 작용getPosts
에서 호출되다Posts.vue
돌연변이에 의해 설정되었기 때문에 아무것도 반환하지 않고 구성 요소@click="getPosts(this.context)"
(이것은 게시물 설정에 매우 효과적임)
<div v-for="post in posts">
<single-post :key="post._id" :post="post" context="feed" />
</div>
당신은 Vuex를 사용해야 한다.mapGetters
조력자 방법
computed: {
...mapGetters({
currPost: 'GET_CURRENT_POST'
})
},
저장 상태에 대한 액세스를 제공하고 반응적이므로 감시자나 추가 계산이 필요하지 않다.
양방향 데이터 바인딩은 이를 실현하는 훌륭한 방법이며, 필요에 따라 고유한 getter/setter 방법을 생성하여 Vue 구성 요소로 가져올 수 있다.
export function mapFields(fields)
{
let computers = {}
for (let field of fields) {
computers[field] = {
get() {
return this.$store.state[field];
},
set(value) {
this.$store.commit(`UPDATE_${field.toUpperCase()}`, value);
}
}
}
return computers;
}
그런 다음 Vue 구성 요소에서 다음을 수행하십시오.
import {mapFields} from 'utils.js'; // or whatever the name of the file
computed: {
...mapFields(['mappedState']),
},
Vue 구성 요소에서 이 .mapedState 업데이트 중:
this.mappedState = ['foo', 'bar'];
트리거:
this.$store.commit('UPDATE_MAPPEDSTATE', ['foo', 'bar']);
그리고 부동산의 데이터를 얻으려면 컴포넌트로 연락하십시오.
// In your template
{{ mappedState }}
// In Vue methods
this.mappedState;
참조URL: https://stackoverflow.com/questions/48650694/update-prop-property-when-vuex-store-changes
'IT이야기' 카테고리의 다른 글
Vuejs는 데이터가 로드된 후에만 하위 구성 요소를 마운트함 (0) | 2022.04.22 |
---|---|
C/C++ 코드에서 주석 제거 (0) | 2022.04.22 |
Java Regex 캡처 그룹 (0) | 2022.04.22 |
Threaten, LocalDate를 사용하여 월의 처음 및 마지막 날짜 가져오기 (0) | 2022.04.21 |
Vuejs + 웹 팩: npm 실행 빌드 느림 (0) | 2022.04.21 |