vuex主要用来集中式管理数据,具体的内容可以查看文档 https://vuex.vuejs.org/zh/api/#vuex-store
vuex提供的两个方法:
mapActions 管理所有事件(行为)
mapGetters 获取数据
那么它该如何使用呢
1.在项目初步搭建完之后可以安装cnpm install vuex -D (项目初步搭建https://blog.csdn.net/chaitong2204/article/details/80943093)
2.自己定义默认页面
找到index.js 导入页面并且修改默认页面,因为之前默认的vue的欢迎页面
3.重点导入vuex
4.新建一个store.js 用来存放方法
之后在main.js里引入store.js, 并且把store暴露在外面
例如我需要定义一个increme方法
我只需要这样定义就可以了,如果是多个方法,直接卸载数组里便可以
下面我把完整的代码放上来,以便参考
store.js中的代码
import Vue from 'vue'
import VueX from 'vuex'
Vue.use(VueX);
var state = {
count:10
}
const mutations = {//处理状态(数据)变化
increme(state) {
state.count++;
}
}
const actions = {
increme:({//处理你要干什么,异步请求,判断,流程控制
commit
})=>{
commit('increme')
}
};
const getters={
count(state){
return state.count;
}
};
//需要导出Store对象
export default new VueX.Store({
state,
mutations,
actions,
getters
})
mai.vue中的代码
<template>
<div>
<button @click="increme">增加</button>
<div>{{count}}</div>
</div>
</template>
<script>
import {mapActions,mapGetters} from 'vuex'
export default {
name: "main",
computed:mapGetters([
'count'
]),
methods:mapActions([
'increme'
])
}
</script>
<style scoped>
</style>
(如果项目较小的时候可以写在一个store,如果项目较大或者为了更加友好的管理可以将store里面的内容进行分解)
------------------------------------------------------------------------------------------------------------------------------------------------------------------
具体的目录结构可以看文档https://vuex.vuejs.org/zh/guide/structure.html