gpt4 book ai didi

javascript - 使用调度后更新状态

转载 作者:行者123 更新时间:2023-12-02 23:39:18 26 4
gpt4 key购买 nike

我正在使用 vuex,并且我有一个 action

storeExpense(context, params){
axios.post('api/expenses', params)
.then( response => {
console.log("Expense Created");
})
.catch( error => {
console.log(error);
});
}

在我的 Expense.vue 上,我使用以下操作:

this.$store.dispatch('storeExpense',this.expense)
.then( response => {
this.modalShow = false
this.$swal(
'Success',
'Expense has been created!',
'success'
)
})

我没有错误,但创建费用后状态没有更新,因此我需要刷新页面以便我的表获取最新数据。

我有一个名为

的突变
mutateExpenses(state, payload){
state.expenses = payload
}

但是,当我在响应后使用它时,它会将整个 state.expenses 对象覆盖为单个对象,因为 this.expense 是单个对象

我是 vuex 新手。

最佳答案

您必须使用在您的操作中调用的突变来更新您的商店。我建议您深入了解 Vuex documentation ,尤其是突变和 Action :)

以下是如何使用商店的示例:

调度 --> 操作 --> 突变

// Your store
const store = new Vuex.Store({
state: {
posts: [],
isLoading: false
},

mutations: {
// Must be called by actions AND ONLY by actions
add(state, post) {
// Add the given post to the 'posts' array in our state
Vue.set(state.posts, state.posts.length, post)
},
busy(state) {
Vue.set(state, 'isLoading', true)
},
free(state) {
Vue.set(state, 'isLoading', false)
}
},
actions: {
create({
commit
}, post) {
commit('busy')
axios.post('https://jsonplaceholder.typicode.com/posts', post)
.then(response => {
// Call the mutation method 'add' to add the newly created post
commit('add', response.data)
})
.catch((reason) => {
// Handle errors
})
.finally(() => {
commit('free')
});
},
}
})

// Your Vue app
new Vue({
el: "#app",
store,
data: {
post: {
title: 'foo',
body: 'bar',
userId: 1
}
},
methods: {
onButtonClicked() {
this.$store.dispatch('create', this.post)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.0/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
<button @click="onButtonClicked">Create Post</button>
<div>Posts : <span v-if="$store.state.isLoading">Requesting</span></div>
<div v-for="post in $store.state.posts">
{{post}}
</div>
</div>

关于javascript - 使用调度后更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56145566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com