vuex的基本介绍
1.vuex的基础概念
Vuex是一个专门为Vue.js应用程序开发的状态管理模式。它采用集中式的存储管理应用所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生改变。
2.vuex的安装
- 第一种安装:命令 npm i vuex --sove
- 第二种:在安装vue时选择安装上vuex
3.vuex的基础使用
- 安装vuex
- 导入vuex包
import Vuex from 'vuex'
Vue.use(Vuex)
- 创建store对象
const store = new Vuex.store({
// state中存放的就是全局共享的数据
state: { count: 0 }
})
- 将store对象挂载到vue实例中
new Vue({
el: '#app',
reader: h => h(app),
router,
// 将创建的共享数据对象,挂载到vue实例中
// 所有的组件,就可以直接从store中获取全局的数据了
store
})
vuex中的主要核心概念如下:
- state
- Mutation
- Action
- Getter
State
state是提供唯一的公共资源的,就像组件里面的data一样
state中的数据和组件data里面的数据是一样的,都是响应式的
// 创建store数据源,提供唯一公共数据
const store = new Vuex.store({
state: {
count: 0
}
})
组件访问State中数据的方式:this.$store.state.全局数据名称
Getter
Getter用于对store中的数据进行加工处理形成新的数据
-
Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
-
Store中数据发生变化,Getter的数据也会跟着变化
// 定义Getter
const store = new Vuex.Store({
state: {
count: 0
},
getters: {
showNum: state => {
return `当前最新的数据时【 ${state.count} 】`
}
}
})
使用Getter的方式:this.$store.getters.名称