vuex状态管理模式简介

一:简介

1:vuex中,有默认的五种基本的对象:

  • state:存储状态(变量)。
  • getters:state的计算属性。 $sotre.getters.fun()。
  • mutations:修改状态,同步的,类似自定义事件。$store.commit('',params)。
  • actions:异步操作。$store.dispath('')。
  • modules:store的子模块,为了开发大型项目,方便状态管理而使用的。

2:小小实列-->数据读取:

安装:npm install vuex --save

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const state = {
    count: 0
}

export default new Vuex.Store({
    state
})

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex/store' // 引入store
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})

hello.vue

<template>
  <div class="hello">
    <h3>{{$store.state.count}}</h3>
  </div>
</template>

3:小小实列-->数据修改同步mutations和异步actions

main.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//存放数据
const state = {
    count: 0
}

//获取state,相对于state的一个计算属性
const getters = {
    getterCount(state, n = 0) {
        return (state.count += n)
    }
}

//同步对数据修改
const mutations = {
    mutationsAddCount(state, n = 0) {
        return (state.count += n)
    },
    mutationsReduceCount(state, n = 0) {
        return (state.count -= n)
    }
}

//异步对数据修改
const actions = {
    actionsAddCount(context, n = 0) {
        console.log(context)
        return context.commit('mutationsAddCount', n)
    },
    actionsReduceCount({ commit }, n = 0) {
        return commit('mutationsReduceCount', n)
    }
}

export default new Vuex.Store({
    state,
    getters ,
    mutations,
    actions
})
hello.vue

<template>
  <div class="hello">
    <h3>{{$store.state.count}}</h3>
    <div>
      <button @click="handleAddClick(10)">增加</button>
      <button @click="handleReduceClick(10)">减少</button>
    </div>
  </div>
</template>

hello.vue

methods: {
    //mutations同步
    handleAddClick(n){
      this.$store.commit('mutationsAddCount',n);
    },
    handleReduceClick(n){
      this.$store.commit('mutationsReduceCount',n);
    }
    //actions异步
    handleActionsAdd(n){
      this.$store.dispatch('actionsAddCount',n)
    },
    handleActionsReduce(n){
      this.$store.dispatch('actionsReduceCount',n)
    }
}

 

 
├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js       # 购物车模块
        └── products.js   # 产品模块






 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值