vuex是什么
vuex 是一个专门为vue.js应用程序开发的状态管理模式。
vuex中,有默认的五种基本的对象:
- state:存储状态(变量)
- getters:对数据获取之前的再次编译,可以理解为state的计算属性。我们在组件中使用 $sotre.getters.fun()
- mutations:修改状态,并且是同步的。在组件中使用$store.commit('',params)。这个和我们组件中的自定义事件类似。
- actions:异步操作。在组件中使用是$store.dispath('')
- modules:store的子模块,为了开发大型项目,方便状态管理而使用的。这里我们就不解释了,用起来和上面的一样。
1 .安装vuex
npm install vuex --save
2 . 新建store/store.js文件,引入vuex
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const state = { count: 1 } const mutations = { increment (state) { state.count++ } } export default new Vuex.Store({ state, mutations })
3.在main.js中引入store
import store from './store/store' new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
4.页面调用count状态
{{ $store.state.count }}
5.用mutations和actions 继续操作store状态
<button @click="add()">add</button> methods: { add () { this.$store.commit('increment') //普通提交封装 } }
5.1 mutations携带参数:
<button @click="add(10)">add</button> methods: { add (count) { // this.$store.commit('increment',count) this.$store.commit({ //对象提交封装 type:'increment', count }) } }
store.js文件: const mutations = { increment (state,count) { state.counter+=count } } //对象提交count更改 payload increment (state) { state.counter+=payload.count }
6.actions是异步操作
const actions = { // 异步操作 acincrement (context) { state.count++ }
使用dispath来触发
this.$store.dispatch('acincrement')
7.getters
const getters = { getterCount(state, n = 0) { return (state.count += n) } } export default new Vuex.Store({ state, mutations, actions, getters })
属性调用:
{{ $store.getters.getterCount }}
7.1getters传参:
{ $store.getters.getterid(10) }}
getterid(state){ return age = >{ return //需要判断的数值 } }