官网教程:https://vuex.vuejs.org/guide/ 2018-10-12
如果你在使用 vue.js
, 那么我想你可能会对 vue 组件之间的通信感到崩溃 。
为什么使用vuex?
vuex主要是是做数据交互,父子组件传值可以很容易办到,但是兄弟组件间传值(兄弟组件下又有父子组件),或者大型spa单页面框架项目,页面多并且一层嵌套一层的传值,那么,用vuex来维护共有的状态或数据会显得得心应手。
Vuex核心概念:
Vuex的核心是store,一个Store保存了应用的所有状态state。
store和全局变量有明显的不同:Vuex stores是反映式的,你不可以直接修改他的值,只能通过成员方法commiting mutations来修改。而成员方法可以理解成观察者模式,会自动更新所有地方。
Vuex入门:
https://segmentfault.com/a/1190000011716027 非常好的一篇入门文章(强烈建议多看几遍!!!)。
状态数据
创建、读、写 user.js
export default {
state: {
perms: [], // 用户权限标识集合
},
getters: {
},
mutations: {
setPerms(state, perms){ // 用户权限标识集合
state.perms = perms;
}
},
actions: {
}
}
调用方法写:
this.$store.commit('setPerms', res.data)
调用方法读:
store.state.user.perms //注意state后的user是模块的名字,真正的变量是perms
$store.commit('switch_dialog')来触发mutations中的switch_dialog方法
vue-cli环境下vuex安装:
npm install --save vuex
Vuex 离线Demo:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue Hello World</title>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
</div>
</body>
<script>
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
new Vue({
el: '#app',
store,
data: {
message: 'Hello Vue.js!'
},
created: function(){
store.commit('increment')
this.message += store.state.count;
}
})
</script>
</html>
效果如下:
Vuex与*.vue组件:
当你创建了Vuex对象之后,并把vuex对象设置到Vue实例中,此时你就可以在任何组件中使用:
this.$store.state.*** 无论哪个组件都可以使用
在组件中使用:
<template>
<div>
<!-- <PatientFSTP v-if="$store.state.patient_tp_both.finished"></PatientFSTP> -->
<PatientFSTP v-if="$store.state.patient_tp_both.finished"></PatientFSTP>
<PatientTP v-else></PatientTP>
</div>
</template>