【Vue】全局数据管理--Vuex

729 阅读1分钟

Vuex是啥

Vuex 是一个专为 Vue.js 应用程序开发的状态(数据)管理(读写)模式

就是可以操作数据的一个对象

安装Vuex

在创建Vue项目时已经安装

如何写---模板

在src/store/index.ts

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

Vue.use(Vuex);   //在Vue.prototype  Vue原型上绑定一个store

const store = new Vuex.Store({

  state: {         //data
    count: 0
  },
  
  mutations: {          //method
    increment (state, payload:{n: number}) {
      state.count+=payload.n
    }
    add(){
      store.commit('increment')   //mutations里的函数可以直接用另一个函数
    }
  },
  
  actions: {
  },
  
  modules: {
  }
});

export default store

在main.ts里

import store from ''
new Vue ({
    store:store //我们给Vue传一个store
}).$mount

解释

store

  • store是一个Vuex.Store对象,是你传state、mutations等这些东西然后生成的一个Vuex.Store对象。
  • 然后store有属性state
  • 都是全局的

state

  1. state就是个对象,就是拿来放数据的

mutations

  1. mutations是一个对象,里面写对state中的数据操作的函数。(相当于methods)
  2. 这些函数只能接受两个参数,第一个就是state。所以这些函数自然可以对state中的数据操作。不用返回值。直接就是对state中数据的操作。
  3. 第二个参数是一个对象payload,如果有很多参数就写成一个对象。

  1. 只能同步

  2. mutations里的函数里可以直接用里面的另一个函数

actions

  1. 异步

如何在组件中用

  • 在组件中导入store,就可以使用store.xxx了
  • 或者直接this.$store.xxx

获得数据——在计算属性中返回

  1. 对象语法
 computed: {
    count () {
      return this.$store.state.count
    }
  }
  1. 类语法
export default class xxx extends Vue {
    get count() {
        return this.$store.state.count
    }
}
  • 为什么在组件里用计算属性?而不是普通数据
  • 因为这个state中得count数据会变的呀。
  • 那我用计算属性,然后依赖和返回的是state中得count数据
  • 我这个计算属性,当里面的依赖state中count数据变了,我们的计算属性也要随着变啊。
  • 如果普通数据的话,就第一次初始化时被赋值为state中得count数据。之后state中得count数据变了,普通数据永远不变?那就没什么意义了。(除非你就说我就是只需要赋值一次,,,,,,,)

操作数据

this.$store.commit(type,payload)

//例如
this.$store.commit('increment',{n:10})
  • type: '函数名'
  • payloda: (可无)这个函数的其他参数组成的对象(state参数不用给,自动给的)