安装
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类似
来源:CSDN
作者:cherrylovedog
链接:https://blog.csdn.net/cherrylovedog/article/details/103698268