vuex的基本使用:
1,安装vuex的依赖包
npm install vuex --save
2,在store.js中引入
imoprt vuex form ”vuex“
Vue.use(vuex)
3,创建store对象
const store = new Vuex.Store({
//state中存放的是全局共享的数据
state:{count:0},
mutations:{},
actions:{}
})
4,将store对象挂载到vue实例上
new Vue({
el:'#app',
render:h=>h(app),
router,
//将创建的共享数据对象挂载到Vue实例中
//所有的组件,就可以直接从store中获取全局数据了
store
})
vuex的核心概念:
vuex的核心概念主要如下:
- state state提供唯一的公共数据源,所有共享 的数据都要统一放到store的state中进行存储
const store = new Vuex.Store({ //state中存放的是全局共享的数据 state:{count:0}, }) //组件中访问state中数据的第一种方式 this.$store.state.全局数据的名称 //组件中访问state中数据的第二种方式 1,从vuex中引入mapState函数 import {mapState} form 'vuex' 通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
方式一: <template> {{$store.state.count}} 方式二: import {mapState} from 'vuex' computed:{ ...mapState(['count']) }
-
- mutatiion mutatiion是用于变更store中的数据 注意⚠️ 1,只能通过mutatiion变更store数据,不可以直接操作store中的数据 2,通过这种方式虽然操作起来比较繁琐,但是可以集中监控所有数据的变化,3,在mutatiion不能写异步方法
store.js文件 export default new Vuex.Store({ state:{ count:0 }, mutations:{ //add 的第一个参数为state对象,第二个参数为传递的参数 add(state, step){ state.count += step } }, actions:{} })
触发 mutations的方法第一种方式,并且mutations在触发的时候传递参数 this.$store.commit('add',3) 触发 mutations的方法第二种方式 import {mapMutations} from 'vuex methods:{ ...mapMutations(['sub']), this.sub(3) }
- action 用于处理异步任务 如果通过一步变更操作Action,而不能使用Mutation,但是在Action中还是通过触发Mumation的方式间接变更数据。
store.js import Vue from "vue" import Vuex from "vuex" Vue.use(Vuex) export default new Vuex.Store({ state:{ count:0 }, mutations:{ //add 的第一个参数为state对象,第二个参数为传递的参数 add(state){ state.count ++ }, addN(state,step){ state.count +=step }, sub(state,step){ state.count -=step } }, // 在actions中不能直接修改state中的数据, //必须通过context.commit()触发某个mutation actions:{ addAsync(context,step){ setTimeout(() => { context.commit('addN',step) },1000) }, subAsync(context,step){ setTimeout(() => { context.commit('sub',step) },1000) } } })
Actions触发的第一种方式 dispatch : this.$store.dispatch('addAsync') Actions触发的第二种方式 mapActions : import {mapActions} from 'vuex'; methods:{ ...mapActions(['subAsync']), this.subAsync(3) }
- getter 用于对store中的数据进行加工处理形成新的数据,类似于vue的计算属性
getters的第一种使用方法 $store.getters.getters里定义的函数名 getters的第一种使用方法 import {mapGetters} from 'vuex' computed:{ ...mapGetters(["showNum"]), },