vuex怎么用

62 阅读1分钟

1697766886251.jpg vuex怎么用 1.npm i vuex 2.建立store文件夹,里面建立index.js文件 import vue from‘vue’ import vuex from ‘vuex’ vue。use(vuex) const store =new vuex.store({ state:{ count:0 } mutations: { setname(state, newval) { state.num = newval }, }, getters: { // state 就是上边定义的公共数据state getter的名字1: function(state) { return 要返回的值 } } actions: { // context对象会自动传入,它与store实例具有相同的方法和属性 action的名字: function(context, 载荷) { // 1. 发异步请求, 请求数据

  // 2. commit调用mutation来修改/保存数据
  
  // context.commit('mutation名', 载荷)
}

}

作者:佑子呀 链接:juejin.cn/post/701332… 来源:稀土掘金 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 }) export default store 3.在main.js中 import store from‘./store’ new Vue({

store }) 4.vue文件中this.store.state.属性名获取数据修改state使用mutationsthis.store.state.属性名获取数据 修改state使用mutations this.store.commit('mutation事件名') btnmutation() { this.store.commit('setbooks',200) // 点击按钮 然后通过commit触发mutation事件 }, getters派生状态 在组件中用this.store.getters.xxx来获取getters派生后的的值

注意: getter定义的时候,第一个参数是state,不能传第二个参数,派生的值通过return返回 actions发起异步请求 我们可以使用Action来修改state,这一点是类似于 mutation的,不同在于:

action中可以通过调用 mutation来修改state,而不是直接变更状态。 action 可以包含任意异步(例如ajax请求)操作。 actions: { getBooks (context, params) { console.log('getbooks的查询参数是', params) axios({ url: 'www.fastmock.site/mock/37d3b9…', method: 'GET' }).then(res => { console.log(res) context.commit('setBooks', res.data.data) }) } },

image.png

image.png

image.png