[英]Vuex can't update component after mutation
在将新内容推送到数组中后,我正在尝试更新组件。 我在 createPost.vue 中创建了一个帖子并将其提交到我的 store.js 文件中,其中存储了我发送到该状态的对象。
我遇到的问题是我太刷新页面以获取数组中的新数据。
createPost.vue:
<script>
import store from '../store'
import axios from 'axios';
export default {
methods:{
postPostToDb(title,content){
const postObj = {
title:title,
content:content,
}
axios.post('http://localhost:5000/v1/api/posts', postObj)
.then((postObj)=>{
this.$store.commit('ADD_POST', postObj);
});
},
},
}
</script>
这是我从 store.js 获取所有数据的地方。
<script>
import store from '../store'
export default {
computed:{
items:function(){
return store.state.posts;
},
},
async created(){
let data = await fetch('http://localhost:5000/v1/api/posts');
data = await data.json();
this.$store.commit('INIT_POST', data);
},
}
</script>
商店.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
posts: [],
},
mutations: {
ADD_POST(state,postObj){
state.posts.push(postObj);
alert(state.posts);
},
INIT_POST(state,postObj){
postObj.forEach(element => {
state.posts.push(element);
});
},
},
actions: {
}
})
您可以尝试像这样使用 mapGetters。
<script>
import store from '../store'
import { mapGetters } from 'vuex'
export default {
computed:{
...mapGetters({
posts: 'getPosts'
})
},
async created(){
let data = await fetch('http://localhost:5000/v1/api/posts');
data = await data.json();
this.$store.commit('INIT_POST', data);
},
}
</script>
现在计算的变量“项目”可以作为“帖子”访问。
在 Store.js 中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
posts: [],
},
getters: {
getPosts(state) {
return state.posts
}
},
mutations: {
ADD_POST(state,postObj){
state.posts.push(postObj);
alert(state.posts);
},
INIT_POST(state,postObj){
postObj.forEach(element => {
state.posts.push(element);
});
},
},
actions: {
}
})
这是Vue 反应性警告。 您需要更新state.posts
对象以使 vuex 反应。 请试试:
ADD_POST(state,postObj){
state.posts = state.posts.concat([postObj])
},
您错误地使用了 Vuex。
如果设置正确,商店应该可以作为this.$store
使用,并且计算的值应该如下所示
computed:{
items:function(){
return this.$store.state.posts;
},
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.