VueX

VueX

什么是VueX?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。这是官网上的介绍,听完是不是很懵,So what?我理解的VueX就是把data的值同步的变化,则需要一个东西把它存储起来,以便于在全局使用。

VueX的使用

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

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

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

  • 安装好VueX就可以创建一些state和mutation

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

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
//store.state 来获取状态对象,通过 store.commit 方法触发状态变更
store.commit('increment')
/输出结果
console.log(store.state.count) // -> 1
//挂载到Vue实例上(ES6)
new Vue({
  el: '#app',
  store
})
//在方法上提交变更
methods: {
  increment() {
    this.$store.commit('increment')
    console.log(this.$store.state.count)
  }
}
复制代码

VueX的核心

  • state:存储store的各种状态
  • mutation: 改变store的状态只能通过mutation方法
  • action: 异步操作方法
  • module: 模块化
  • getter: 相当于计算属性,过滤出来一些值
  • state的使用
const store = new Vuex.Store({
    //存放状态信息
    state: {
        counter:1000,
    },
 //拿到counter的值
<h2>{{$store.state.counter}}</h2>
    

复制代码
  • mutation的使用
 mutations: {
        //方法,改state提交mutation
        //mutation响应规则
        //mutation无法进行异步更新
        increment(state) {
            state.counter++

        },
      }  
  //在方法中提交mutation
  methods: {
    addition(){
      //提交store的信息
      this.$store.commit('increment')
      }

复制代码
  • action的使用
const store = new Vuex.Store({
    //存放状态信息
    state: {
        Info: {
            name : 'kobe',
            age:20,
            height : 1.98
       }
    },
    
    actions:{
        //进行异步操作
        //context上下文
        //异步可以用setTimeout
        aupdateInfo(context){
            setTimeout(() =>{
                context.commit('updateInfo')

            },1000)
        }
    }
    methods: {
        updateInfo() {
      // this.$store.commit('updateInfo')
      // dispatch:含有异步操作,例如向后台提交数据,写法:this.$store.dispatch('action方法名',值)

//commit:同步操作,写法:this.$store.commit('mutations方法名',值)
      this.$store.dispatch('aupdateInfo')
      },
  }
}
复制代码
  • getter的使用
  getters: {
        //vuex中的计算属性,用于筛选数据
        powerCounter(state) {
            return state.counter * state.counter
        }
  //挂载
  <h2>{{$store.getters.powerCounter}}</h2>

复制代码
  • module的使用
    modules :{
//state比较臃肿时在modules中划分,有自己的getters,mutations,actions等
        a:modulesA
    }
 const modulesA = {
    state : {
        name : 'zhangsan'
    }
    mutation: {},
    getter: {}

}


复制代码

注意

action和mutation的区别:

  • action异步操作,mutation同步操作
  • action提交的是mutation,而不是直接变更状态
posted @ 2020-10-27 18:40  孙同学你好  阅读(68)  评论(0编辑  收藏  举报