VUEX
简介
- vuex是管理组件全局状态的一种机制,可以实现组件之间的数据共享
- 创建一个全局store,实现组件数据传递
- 存储在vuex中的数据都是响应式的,能实时保持数据与页面的同步
使用
-
安装依赖包
npm install vuex --save
-
导入vuex包
import Vuex from 'vuex' Vue.use(Vuex)
-
创建store对象
const store = new Vuex.Store({ // state 中存放全局共享的数据 state: { count: 0 } })
-
将store对象挂在到vue实例中
new Vue({ el:'#app', render:h=>h(app), router, store })
vueUI创建vue项目
- cmd命令中
vue ui
打开vue可视化面板 - 按照步骤创建包含vuex项目的vue项目
一、State
介绍
-
提供唯一的公共数据源,所有共享的资源都要统一放到Store中的State中进行存储
const store = new Vuex.Store({ state:{count: 0} })
组件访问State中的数据
方式一
this.$store.state.全局数据名称
方式二
// 1.从vuex中导入mapState函数
import { mapState } from 'vuex'
// 2.将全局属性映射为当前的计算属性
computed: {
...mapState(['count'])
}
二、Mutations
介绍
-
mutations表示:变化
-
用于修改store中的数据
-
只能通过
Mutations
修改store中的数据,不能直接通过this.$store.state.全局数据名称 = 值
的方式修改数据 -
这种方式虽然操作起来稍微繁琐,但是可以集中监控所有数据的变化
mutations中创建函数
mutations: {
add(state) {
// 变更状态
state.count++
}
}
组件中调用mutations函数
方式一
- 关键词:commit
methods: {
handle() {
this.$store.commit('add')
}
}
方式二
- 从vuex中导入mapMutations函数
- 将需要的mutations函数映射为组件中的methods方法
import {mapMutations} from 'vuex'
methods: {
...mapMutations(['sub', 'subN']),
subHandle1() {
this.sub()
},
subHandle2() {
this.subN(4)
}
}
在mutations函数传参
定义函数参数
mutations: {
addN(state,step) {
state.count += step
}
}
调用函数传参
methods: {
handle() {
this.$store.commit('addN',3)
}
}
注意
- 不要在mutations中执行异步操作,例如setimeout()
三、Actions
介绍
- 用于处理异步操作
- 要在Acitons中通过异步操作变更数据,不能在mutations中执行异步操作
- 但是在actions中还是要通过触发mutations中的函数来变更数据,不能直接在actions中变更数据
在actions中定义异步操作
actions: {
addAsync(context) {
setTimeout(()=>{
context.commit('add')
},1000)
}
}
组件中调用actions的函数
方式一
- 关键词:dispatch
methods: {
handle(){
this.$store.dispatch('addAsync')
}
}
方式二
- 导入vuex中的
mapActions
函数 - 将需要的actions函数映射为组件的methods方法
import { mapActions } from 'vuex'
methods: {
...mapActions(['addAsync','addAsyncN']),
subHandle3() {
this.subAsync()
}
}
直接调用
-
可以直接在template的标签中调用mapActions或mapMutations中传递的方法
<button @click="addAsync">异步+1</button> methods: { ...mapActions(['addAsync','addAsyncN']), subHandle3() { this.subAsync() } }
actions定义传参函数
actions: {
addAsync(context,step) {
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
}
组件中调用参数函数
methods: {
handle() {
this.$store.dispatch('addAsync',8)
}
}
四、Getters
介绍
- Getters用于对store中的数据加工处理形成新的数据
- 对store已有数据加工处理,类似于vue的计算属性
- Store中数据发生变化,Getters的数据也会发生变化
用法
getters: {
showNum: state => {
return '当前最新的数量是['+ state.count +']'
}
}
或者:
getters: {
showNum(state) {
return '当前最新的数量是[' + state.count + ']'
}
},
调用getters方法
方式一
this.$store.getters.名称
例如:<h3>{{ $store.getters.showNum }}</h3>
方式二
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showNum'])
}
引入后直接在标签中使用:
<h3>{{ showNum }}</h3>