Vuex
1.vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
安装
cnpm install vuex --save
在main.js中引用:
import Vuex from 'vuex' Vue.use(Vuex)
2.使用vuex
Vuex核心是一个store仓库,这个仓库的作用是用来管理应用中的state(状态),状态可以理解为所有组件共享的并且可以进行更改的对象
vuex的getter:组件获取state
vuex的action:组件触发动作
vuex的mutation:修改state
main.js
const store = new Vuex.Store({ //创建一个仓库 state: { showDagger: true, // 定义一个状态 }, mutations: {// 定义 mutation ,更改 Vuex 的 store 中的状态的唯一方法是提交mutation daggerCtrl (state) { // 一定要传入state,并且是第一个参数 state.showDagger = !state.showDagger // 将showDagger值取反 } } }) /* eslint-disable no-new */ new Vue({ el: '#app', router, // 将router对象传给vue,这样就可以通过this.$router获取到router对象了 store, // 将store对象传给vue,这样就可以通过this.$store获取到store对象了 template: '<App/>', components: { App } })
App.vue
this.$store.commit('daggerCtrl')使用commit(提交)唤醒名为daggerCtrl的mutation
组件.vue
<template>
<div class="dagger" v-if="this.$store.state.showDagger">
<h1>Dagger</h1>
</div>
</template>
浙公网安备 33010602011771号