1. 安装
npm i vuex -s
在项目的根目录下新增一个store
文件夹,在该文件夹内创建index.js
。
2. 使用
1、初始化store
下index.js
中的内容:
import Vue from 'vue'
import Vuex from 'vuex'
//挂载Vuex
Vue.use(Vuex)
//创建VueX对象
const store = new Vuex.Store({
state:{},
mutations:{},
actions:{}
})
export default store
2、在Vue实例上挂载
//main.js
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store, //将创建的Vuex实例挂载到这个vue实例中
render: h => h(App)
})
3、具体使用
-
在组件中使用Vuex中的数据
<template> <div id='app'> <h1>{{ $store.state.name }}</h1> </div> </template>
补充:如果是在方法中使用数据,则是:
this.$store.state.name
-
修改Vuex中的数据(Mutations)
mutations
是操作state
数据的方法的集合,比如对数据的修改、增加、删除。import Vue from 'vue' import Vuex from 'vuex' //挂载Vuex Vue.use(Vuex) //创建VueX对象 const store = new Vuex.Store({ state:{ name:'VueX' }, mutations:{ edit(state){ state.name = 'Byu' }, //使用Vue.set增删state editAge(state, payload) { Vue.set(state, payload) } } }) export default store
-
调用
mutations
中的方法this.$store.commit('edit') this.$store.commit({ type: 'editAge', {age: 18} })
Vue.set
增删state
数据使用
Vue.set
增删state
中的成员,增删的对象{age: 18}
,在调用mutations中的editAge
方法时,以参数的形式传入。在store中的mutations里,传入的参数又被
payload
参数接收,所以在mutations里Vue.set(state, payload)
,payload
等于{age: 18}
。 -
Mutation传参
单个参数:
this.$store.commit('edit',15)
多个参数:
this.$store.commit('edit',{age:15,sex:'男'})
-
Actions —— 异步操作
Actions方法中有两个默认参数:
context
上下文(相当于箭头函数中的this)对象;payload
挂载参数。actions:{ aEdit(context,payload){ setTimeout(()=>{ context.commit('edit',payload) },2000) } }
如上,
aEdit
方法中的setTimeout
是异步操作,所以需要使用actions
。 -
调用Actions中的方法
this.$store.dispatch('aEdit',{age:15})
让
count
每隔两秒进行一次增加state: { count: 1 }, mutations: { add(state){ state.count++ } }, actions:{ aAdd(context){ setInterval(()=>{ context.commit('add') },2000) } }