vuex可以实现多组件共享状态
提供全局状态(全局变量)管理的模块(插件)
将全局变量放在一块统一管理
1.所有组件都能用
2.有其中一上组件发生改变,其它页面都会发生改变
什么时候用到?多组件共享状态
1.有多个组件用了同一变量
2.变量发生改变之后组件要发生变化
使用方式
1.创建配置
引入vue
引入vuex
使用Vuex
创建Vuex的store对象
抛出
2.注册store
参考路由在main.js的实例中注册store,就会有
s
t
o
r
e
对
象
3.
使
用
全
局
状
态
值
t
h
i
s
.
store对象 3.使用全局状态值 this.
store对象3.使用全局状态值this.store.state
4.修改全局状态值
vueX中规定 修改全局状态值必须通过mutations里的方法
this.
s
t
o
r
e
.
c
o
m
m
i
t
(
′
m
u
t
a
i
o
n
里
的
函
数
名
′
,
传
递
的
参
数
)
5.
其
他
优
化
a
c
t
i
o
n
s
存
放
异
步
操
作
1.
减
少
异
步
代
码
的
重
复
2.
统
一
管
理
异
步
请
求
3.
时
间
旅
行
对
象
组
件
里
通
过
store.commit('mutaion里的函数名', 传递的参数) 5.其他优化 actions 存放异步操作 1. 减少异步代码的重复 2. 统一管理异步请求 3. 时间旅行 对象 组件里通过
store.commit(′mutaion里的函数名′,传递的参数)5.其他优化actions存放异步操作1.减少异步代码的重复2.统一管理异步请求3.时间旅行对象组件里通过store dispatch触发action里的方法
action 里执行异步 执行完毕再通过commit 触发mutation
getters 当成vuex里的计算属性
是一个对象
创建一个新的变量 该变量和state值相互关联
辅助函数
值 state getters
将值映射到计算属性
mapState mapGetters
函数 mutations actions
将函数映射到methods
/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { // 全局状态 全局变量
toggle: true
},
mutations: { // 变异,突变,转变,改变
// 本质是一个对象 想修改state里面的值必须通过mutation里的方法
changeToggle(state, params) {
state.toggle = !state.toggle
console.log(params)
}
},
actions: { // 行动
},
getters: {
},
modules: { // 模块
}
})
App.vue
<template>
<div id="app">
<componentA></componentA>
<componentB></componentB>
<componentC></componentC>
</div>
</template>
<script>
import componentA from './components/A.vue'
import componentB from './components/B.vue'
import componentC from './components/C.vue'
export default {
name: 'App',
components: {
componentA,
componentB,
componentC
}
}
</script>
<style>
</style>
A.vue
<template>
<div>
组件A
<button @click="toggle">atoggle</button>
</div>
</template>
<script>
export default {
methods: {
toggle() {
this.$store.commit('changeToggle', {id: 123, type: 'abc'})
}
}
}
</script>
<style>
</style>
B.vue
<template>
<div>
组件B
<button @click="toggle">btoggle</button>
</div>
</template>
<script>
export default {
methods: {
toggle() {
this.$store.commit('changeToggle', {id: 123, type: 'abc'})
}
}
}
</script>
<style>
</style>
C.vue
<template>
<div>
组件C
<div class="demo" v-if="this.$store.state.toggle">组件C的state</div>
</div>
</template>
<script>
export default {
data() {
return {
}
}
}
</script>
<style>
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App)
}).$mount('#app')