第一步安装 vuex(安装在生产环境)
npm install vuex
第二步 src 下新建 store 文件夹 用来专门放状态管理, store 文件夹下新建四个 js 文件 index.js actions.js mutations.js getters.js(后面会一一介绍这几个文件的作用)
第三步 main.js 中引入 store
import store from './stroe'
main.js 中实例化的时候使用 store
- new Vue({
- el:'#app',
- stroe,// 挂载 stroe
- router,
- template:'<App>' ,
- components:{App}
- })
基础工作做完了, 可以开始第一个 demo 了
vuex 共分四个模块, components 即组件, 数据展示修改层面, actions 业务处理事务转发, mutations 具体的业务逻辑处理, getters 拿到处理好后的数据返给 components
四个模块可以都写在 index.js 里也可以单独写, 然后在 index.js 里引入, 这里是单独写再引入的
- index.js
- import Vue from 'vue'// 引入 vue
- import Vuex from 'vuex'// 引入 vuex
- import * as actions from './actions'
- import * as mutations from './mutations'
- import * as getters from './getters' //* 即所有
- Vue.use(Vuex)
- onst state = {
- number:123
- }
- // 注册上面各个模块
- const store = new Vuex.Stroe({
- state,getters,actions,mutations
- })
- expoort default store
state{} 数据存放位置, 现在里面有个 number 数据为 123
其实现在已经可以在组件里面用这个数据了, 通过 this.$store.state.number 只是官方不建议这么用
从页面开始
- componentsA.vue
- <template>
- <div>
- <p>vuex 中的数据 {{number}}</p>
- <button @click='modifynumber'> 修改 number</button>
- </div>
- </template>
- <script>
- import{mapActions,mapGetters} from 'vuex' // 语法糖
- //mapActions 相当于 this.$store.dispatch('请求类型', 数据) 发送请求
- //mapGetters 相当于 this.$store.getters.number
- export default{
- data(){
- retrun{
- }
- },
- methods:{
- ...mapActions(
- ['modifynumber']// 提交方法
- ),
- },
- computed:{
- ...mapGetters(['number']) // 获取 state 中的数据
- }
- }
- </script>
mapActions 写在 methods 中 mapGetters 写在 computed 中
mutations 中做具体的业务逻辑处理
- mutations.js
- export const modifynumber = (state) =>{
- state.number ++
- }
- getters.js
- export const number = (state) =>{ return state.number}
大概就是这些了
I love three things in the world: the sun, the moon, and you. The sun for day, the moon for night, and you forever.
浮世万千, 吾爱有三, 日 月 与卿, 日为朝, 月为暮, 卿为朝朝暮暮.
来源: https://www.cnblogs.com/wong-do/p/9500327.html