vuex的特点
- 多组件共享状态: 多个组件使用同一个数据
- 任何一个组件发生改变, 其他组件也要跟着发生相应的变化
基本使用
- 安装vuex
npm install vuex
创建实例
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
const state = {
name : '张三',
age : 18
}
const mutations = {
// 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
changeName (state, params) {
state.name = params.name
},
changeAge (state, params) {
state.age = params.age
}
}
const actions = {
// Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation
actionsChangeAge ( context, params) {
context.commit('changeAge', params)
}
}
const getters = {
// Getter 接受 state 作为其第一个参数
doubleAge (state) {
return state.age * 2
}
// 也可以使用箭头函数的简写
// doubleAge: state => state.age * 2
}
const store = new Vuex.Store({ // 创建全局状态管理的实例
state, // 共同维护的全局状态
mutations, // 处理数据的唯一途径, 修改state的数据只能通过mutations
actions, // 数据的异步操作处理
getters // 获取数据并渲染
})
// 导出并在main.js里面引用&注册
export default store
import Vue from 'vue'
import App from './App.vue'
import store from './store/index'
Vue.config.productionTip = false
new Vue({
store, // 全局使用
render: h => h(App),
}).$mount('#app')
<template>
<div>
<h2>组件</h2>
<!-- 组件可以通过this.$store.state 获取store中的数据 -->
name: {{ this.$store.state.name }} <br>
age: {{ this.$store.state.age }}
<button @click="change">修改年龄</button>
</div>
</template>
<script>
export default {
methods: {
change () {
// 此方法一般用于网络请求
// dispatch: 调用actions里面的方法, 再让actions里面的方法
// 通过commit 调用mutations里面的方法
this.$store.dispatch('actionChangeAge', { age: 120 })
},
changeName () {
// 通过$store.commit直接调用store实例中mutation里面的方法
// 参数1: 要调用mutation里面的方法名, 参数2: 要传输的数据
this.$store.commit('changeName', { name: '宝宝', age: 19})
}
}
}
</script>
数据都存在this中的$store中, 可以console.log(this) 查看里面的数据
5 大核心 - state 和 mutation 是必须的
✨ | |
---|---|
state | 存放基本数据 |
getters | 从state基本数据派生出的数据(类似vue中的computed) |
mutations | Store中更改state数据状态的唯一途径 |
actions | 通过dispatch触发actions, actions在通过commit触发mutations。一般用于处理异步操作 |
modules | 模块化Vuex |
辅助函数
帮助我们减少代码量
- 四个方法
值类型向计算属性(computed)映射
- mapState 将全局状态管理的state值映射到使用组件的计算属性
- mapGetters 将全局状态管理的getters值映射到使用组件的计算属性中
函数类型向methods映射
- mapMutations 将mutation的方法映射到methods里面
- mapActions 将actions里面的方映射到methods里面
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
computed: {
// 可直接在实例中使用
...mapGetters(['doubleAge'])
},
methods: {
...mapMutations(['changeName', 'changeAge']),
change () {
// 可以使用this.changeName调用
this.changeName({ name: '张三丰' })
},
}
}