vuex的五个核心概念

VueX 是一个 Vue.js 应用设计的状态管理构架,一个状态管理工具。

Vuex有五个核心概念stategettersmutationsactionsmodules
        state  状态   存储vuex的基本数据
        getters  类似单个组件的计算属性
        mutation    里面定义提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的事件类型 (type) 和一个 回调函数 (handler)。
            commit传递的时候可以传递参数(参数被称为载荷(payload))
        action   与mutation的功能基本相同

           不同点:Action 提交的是 mutation,而不是直接变更状态; Action 可以包含任意异步操作。
        module   对vuex进行模块化,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构更清晰,方便管理。

下面的代码会让你对这个五个核心概念更加了解。

app.vue

<template>
  <div id="app">
    <h2>------------module里面的内容</h2>
    <h3>{{$store.state.a.name}}</h3>
    <h3>{{$store.getters.fullName}}</h3>
    <h3>{{$store.getters. fullName2}}</h3>
    <h3>{{$store.getters. fullName3}}</h3>
    <button @click="updateName">修改name</button></button>
    <button @click="asyncUpdateName">异步修改name</button></button>
    <h2>------------</h2>

    <h2>{{$store.state.info}}</h2>
    <button @click='updateInfo'>添加</button>
    <h2>----------app内容</h2>
    <h2>{{$store.state.counter}}</h2>
    <button @click='add'>+</button>
    <button @click='sub'>-</button>
    <button @click='addCount(5)'>+5</button>
    <button @click='addCount(15)'>+10</button>
    <h2>--------------app内容:getters相关</h2>
    <h2>{{$store.getters.pfCounter}}</h2>
    <h2>{{$store.getters.bigAge}}</h2>
    age > 25的数量<span>{{$store.getters.bigAgeSum}}</span>
    自定义age<span>{{$store.getters.moreAge(10)}}</span>
    <home/>
    
  </div>
</template>

<script>
import Home from './components/Home'
export default {
  name: 'App',
  components:{
    Home
  },
  data(){
    return {
      counter:0
    }
  },
  methods: {
    add(){
        this.$store.commit('increment')
    },
    sub(){
      this.$store.commit('decrement')
    },
    addCount(count){
      // 普通提交
        // this.$store.commit('incrementCount',payload)
        // 特殊的提交封装
        this.$store.commit({
          type:'incrementCount',
          count
        })
    },
    updateInfo(){
      // this.$store.commit('updateInfo')
      this.$store.dispatch('aUpdateInfo','携带的信息').then((value) => {
        console.log(value)
      })
    },
    updateName(){
      this.$store.commit('updateName')
    },
    asyncUpdateName(){
      this.$store.dispatch('aUpdateName')
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

index.js

import Vue from 'vue'
import Vuex from 'vuex'
// 安装插件
Vue.use(Vuex)
    // 创建对象
const moduleA = {
    state: {
        name: 'nihao'
    },
    mutations: {
        updateName(state) {
            state.name = 'hhhh'
        }
    },
    actions: {
        aUpdateName(context) {
            setTimeout(() => {
                context.commit('updateName')
                console.log(context)
            }, 1000)
        }
    },
    getters: {
        fullName(state) {
            return state.name + '1111'
        },
        fullName2(state, getters) {
            return getters.fullName + '22222'
        },
        fullName3(state, getters, rootState) {
            return getters.fullName + rootState.counter
        }
    }
}
const moduleB = {
    state: {},
    mutations: {},
    actions: {},
    getters: {}
}
const store = new Vuex.Store({
        state: {
            counter: 1000,
            stu: [{
                name: 'lm',
                age: 22
            }, {
                name: 'xh',
                age: 25
            }, {
                name: 'kb',
                age: 36
            }],
            info: {
                name: 'coo',
                age: 33
            }
        },
        mutations: {
            //定义方法  默认已有参数state
            increment(state) {
                state.counter++
            },
            decrement(state) {
                state.counter--
            },
            incrementCount(state, payload) {
                console.log(payload);
                // state.counter = state.counter + count
                state.counter = state.counter + payload.count
            },
            updateInfo(state) {
                state.info.name = "llll"
                    // state.info["address"] = 'ts'
                    // delete state.info.age

            }
        },
        actions: {
            // context 上下文
            aUpdateInfo(context, payload) {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        console.log(payload)
                        context.commit('updateInfo')
                    }, 1000);
                    resolve('success')
                })
            }
        },
        getters: {
            //类似计算属性
            pfCounter(state) {
                return state.counter * state.counter
            },
            // 年龄大于25的学生
            bigAge(state) {
                return state.stu.filter(s => s.age > 25)
            },
            bigAgeSum(state, getters) {
                return getters.bigAge.length
            },
            moreAge(state) {
                return function(age) {
                    return state.stu.filter(s => s.age > age)
                }
            }

        },
        modules: {
            a: moduleA,
            b: moduleB
        }
    })
    // 导出stored对象
export default store

 显示结果:

注意:更改state里面的状态只能通过mutation修改

           高版本的cli可以使一些方法具有响应式

                 state.info["address"] = 'ts'
                delete state.info.age

            this.$store.commit的提交方式有两种,传递的参数接收的方式也有区别

一个浏览器对vue进行管理的浏览器插件  Devtools

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值