Vuex

小型项目

Vuex 是一个全局数据管理器;

不过小项目的话可以不用 Vuex ;直接使用根组件保存用户数据;(因为每一个组件都可以访问到根组件)

大型项目的话就得使用 Vuex 来管理数据了;



开始

每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。Vuex 和单纯的全局对象有以下两点不同:

  1. Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

  2. 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。



使用

安装

> npm i vuex

配置
创建文件 src/store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex)

const store = new Vuex.Store({
    // 数据源
    state: {
        count: 0
    },
    
    // 修改数据的方法,第一个参数是 state对象
    mutations: {
        change(state){
            state.count++;
        }
    },
    
    // 查询数据,第一个参数是 state对象
    getters: {
        getCount(state){
            return state.count;
        }
    },
    
    actions: { }
})

export default store;

main.js

import store from './store'
new Vue({
  render: h => h(App),
  store
}).$mount('#app')

使用

读取 getters 的数据:

// this.$store.getters.方法名
// 如:
this.$store.getters.getCount

调用 mutation 中的方法修改数据

// commit()  用来触发 mutation 中的函数
// commit('函数名称', 自定义参数)
this.$store.commit('change')

action中的函数
第一个参数:context 实际上就是一个 store对象,之前通过 $store.commit来调用 mutation中的函数来修改数据

$store 就是一个 store对象,可以通过 commit 调用函数
而这里的 context也是这个对象,所以也可以通过 commit 调用函数

// 定义
// 第一个参数:context 实际上就是一个 store对象
// 第二个参数:自定义参数
actions: {
    CHANGE_COUNT(context){
        console.log(context)
    }
}
// 使用
// dispatch()  用来触发 action中的函数
// dispatch('函数名称', 自定义参数)
this.$store.dispatch('CHANGE_COUNT')

通过 action 来修改数据
首先在 action中调用mutation中修改数据的方法

actions: {
    CHANGE_COUNT(context, '自定义参数 可选'){
    
    	// context: store 对象
    	// 可以通过 commit 来修改数据
    	// 可以通过 getters 来查询数据
    	// 可以通过 dispatch 来访问 actions
        const {commit, dispatch, getters} = context;
        
		// commit(函数名, 自定义参数)
        commit('change')
    }
}
// 调用 action中的函数
// this.$store.dispatch( 函数名, 自定义参数)

this.$store.dispatch('CHANGE_COUNT')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章