在vuex中使用moudle

一个人想着一个人 提交于 2019-12-26 04:55:16

安装

npm install vuex --save

引入

//main.js
import store from './store'//引入store
new Vue({
  el: '#app',
  router,
  store,
  components: {
    App
  },
  template: '<App/>'
})

新建store文件夹

目录结构

store
│ index.js
│ 
├─feeds
│  actions.js
│  getters.js
│  index.js
│  mutation-type.js
│  mutations.js
│  state.js
│  
└─movies
  ``actions.js
  ``getters.js
  ``index.js
  ``mutation-type.js
  ``mutations.js
  ``state.js

index.js

/*
 * @Author: your name
 * @Date: 2019-12-25 13:13:28
 * @LastEditTime : 2019-12-25 13:13:50
 * @LastEditors  : Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /gitlab-test/src/store/index.js
 */
import Vue from 'vue';
import Vuex from 'vuex';
import feeds from './feeds';
import movies from './movies';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    feeds,
    movies
  },
});

Feeds/index.js

/*
 * @Author: your name
 * @Date: 2019-12-25 13:15:31
 * @LastEditTime : 2019-12-25 13:15:43
 * @LastEditors  : Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /gitlab-test/src/store/feeds/index.js
 */
import state from './state';
import mutations from './mutations';
import actions from './actions';
import getters from './getters';

export default {
  namespaced: true, //多出的一行
  state,
  mutations,
  actions,
  getters
};

Feeds/state.js

export default {
    msg:'初始化显示数据',
    count:1
}

Feeds/mutations-types.js

export  const GET_MSG = 'get_msg'

Feeds/mutations.js

import * as types from './mutation-types'
export default {
    [types.GET_MSG](state,msg){
        state.msg = msg
    }
}

Feeds/actions.js

import * as types from './mutation-types'
export default {
    getMsg({commit,state},msg){
        commit('GET_MSG',msg)

    }
}

页面中使用

State:

直接写在html中

this.$store.state.feeds.msg

getters

 computed:{
    ...mapGetters({
      addCount:'feeds/addCount'
    })
  }

其他actions,mutations类似

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!