1、vuex是什么
Vuex是Vue官方提供的一个插件,是一个状态管理工具。用来集中处理项目中组件共用的数据。
当项目比较庞大,数据比较复杂时可以使用Vuex进行管理
2、vuex的属性
- state
- mutations
- actions
- getters
- modules
3、Vuex的使用
<1>下载Vuex
npm install --save vuex
<2>配置仓库 创建新文件【index.js】src——>>store——>>index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 使用插件
Vue.use(Vuex)
// state 仓库存储数据
const state = {
count: 1
}
// 修改state的唯一手段
const mutations = {
ADD(state){
// console.log(state);
state.count++
}
}
// 与mutations类似;但是可以书写自己的业务逻辑但不能直接修改state中的数据;也可以处理异步
const actions = {
add(context){
// console.log(context);
context.commit('ADD')
}
}
// 类似于vue中的computed,让组件获取仓库的数据更加方便
const getters = {
}
// 对外暴露store类的实例对象
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
在入口文件【main.js】中对仓库进行使用
// 引入store仓库
import store from './store/index.js'
new Vue({
render: h => h(App),
router,
// 注册仓库
store
}).$mount('#app')
4、Vuex实现模块化开发
可以将大仓库的属性拆分成多个小仓库进行管理
// 引入定义的小仓库
import home from './home.js'
import search from './search.js'
// 对外暴露store类的实例对象
export default new Vuex.Store({
modules: {
home,
search
}
})
5、使用仓库的数据
<1>使用state中数据
方式一: this.$store.state.count
方式二:通过mapState辅助函数
import { mapState } from 'vuex'
computed: {
...mapState(['count'])
}