Vuex----vue的状态管理模式

Vuex----vue的状态管理模式

博客说明

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!

简介

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化,Vuex 是繁琐冗余的,一般用于大型项目。

官方文档

https://vuex.vuejs.org/zh/guide/state.html

安装

进入到项目目录里面

cnpm install vuex --save

核心概念

State(单一状态树)

意思就是用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源”而存在。这也意味着,每个应用将仅仅包含一个 store 实例

// 创建一个 Counter 组件
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return store.state.count
    }
  }
}

Getter(State的派生)

有时候需要从store 中的 state 中派生出一些状态,所以就会用到getter了

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})

Mutation(State唯一的改变方法)

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)

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

Action(提交而不改变)

Action 提交的是 mutation,而不是直接变更状态,它 可以包含任意异步操作。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

Module(分割模块)

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,可以将store对象分割成一些模块。

感谢

vuex

以及勤劳的自己

发布了155 篇原创文章 · 获赞 317 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45163122/article/details/104901507