vuex 用法

目录结构如下

--store

    --modules

        --one.js

        --two.js

        --three.js

   index.js

 

直接上代码:

// one.js 文件

import http from '$path'   // 引入请求方法

const state = {

  name: null,

  age: null

}

const mutations = {

  updateSomting : (state, payload) =>  {

    state.name = payload

  }

}

const actions = {

  functionName1 ({commit, state}, payload) {

    commit(updateSomting, payload)

  },

  functionName2 ({commit, state}, payload) {

    return new Promise((resolve, reject) => {

        http.get("$url").then((res) => {

          if(res) {

             let con = res.content

             commit('updateSomting', con)

          }

        }) .catch (err => {

           console.log("错误处理=====")

           reject(err)

        })

    })

  }

}

 

erport {

  namespaced: true,
  state,
  mutations ,
  actions

}

 

// index.js 文件

import Vue from 'vue'

import Vuex from 'vuex'

import one from './modules.one'

 

Vue.use(Vuex)

export default new Vuex.Store {

  namescaped: true,

  state: {

  },

  modules: {

    one

  },

 mutations: {

   updateSomting : (state, payload) =>  {

      state.name = payload

    }

 },

 actions:{

   functionName1 ({commit, state}, payload) {

      commit(updateSomting, payload)

    }

 },

getters: {
   name:  state => state.one.name
}

}

 

 // 在主入口文件main.js中引入store index.js 文件 eg:

import store from 'store/index'

挂在到app 组件上
new Vue({
i18n,
router,
store,
render: h => h(App)
}).$mount('#app')

 

// 其他组件中使用store 中state以及触发action用法

1)获取全局state 状态 

     this.$store.getters.stateName

2) 触发store actions 

    this.$store.dispatch('one/functionName2', payload)   // 涉及到异步获取服务端数据

3)更新 store 下 mutations     

     this.$store.commit('one/updateSomting ',payload)   // 同步更新 state

  

 

 

    

posted @ 2020-10-15 17:58  wangshiqiao  阅读(108)  评论(0)    收藏  举报