Vuex 学习笔记

组件之间共享数据的方式 小范围

  • 父向子:v-bind属性绑定 简写:
  • 子向父:v-on 事件绑定 简写@
  • 兄弟组件之间共享数据:EventBus

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享

// 安装
npm install vuex --save
// 导入
import Vuex from 'vuex'
Vue.use{Vuex}
// 使用
const store = new Vuex.Stor({
    // state中存放的就是全局共享的数据
    state:{ count :0 }
})

组件访问State中数据的第一种方法

this.$store.state.全局数据名称

组件访问State中数据的第二种方法

 mapState 函数

// mapState 函数
import { mapState } from 'vuex';
computed:{
    ...mapState(['全局数据名称'])
}

不可以直接修改全局变量

Mutation 用于变更 Store 中的数据

const store = new Vuex.Store({
    state:{
        count:0
    },mutations:{
        add(state){
            // 变更状态
            state.count++
        }
    }
})



// 触发mutation
methods:{
    handlel(){
        // 触发mutations的第一种方式
        this.$store.commit('add')
    }
}

Mutation 传参

// 定义
const store = new Vuex.Store({
    state:{
        count: 0
    },mutations:{
        addN(state,step){
            state.count += step
        }
    }
});


// 调用

this.$store.commit('addN',3);

this.$store.commit() 是触发mutations 的第一种方式,第二种方式:

import { mapMutations } from "vuex"

methods:{
    ...mapMutations(['add' , 'addN']);
}

第二种方法使用this.方法就可以调用全局数据

 

是否使用mutation取决于除修改变量外是否有其他操作

mutations方法里面不能执行异步操作

 

 

Action用于处理异步操作

使用方法:

actions:{
    addAsync(context){
        setTimeout(() => {
            // 在actions 不能直接修改state中的数据,没有权限,只有mutation有权限
            // 必须通过context.commit() 触发某个 mutation 才行
            context.commit('add')
        } , 1000);
    }
}

// 调用
actionAct() {
    this.$store.dispatch('addAsync')
}

第二种导入方法

import { mapActions } from 'vuex'

subAsync(context){
    setTimeout (() => {
        context.commit('sub')
    },1000)
}

methods:{
    ...mapActions(['subAsync'])
}

 

 

getter

用于对Store中的数据进行加工处理形成新的数据,包装的作用

store的数据变化,getter的数据也会变化

getters:{
    showNum : state => {
        return state.count
    }
}

第二种调用

import { mapGetters } from 'vuex' 

computed:{
    ...mapGetters(['showNum'])
}

 

 

modules

Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = createStore({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

 

posted @ 2022-09-23 19:45  圆子同学  阅读(25)  评论(0)    收藏  举报