vuex的使用
vue - vuex - 的使用
前端用到 vue 框架的伙伴们终究是绕不过 vuex
我理解的 vuex 简单用法(但是却很适用,就会这一个就基本可以用vuex了):
比如: AA、BB 两个组件同时要控制 CC 组件的 显示 / 隐藏。 是不是要一个开关 ?
那个开关假如 我们 定义 为 flag 变量。 当 flag 为 true 时,CC 组件就 显示, 当 flag 为 false 时,就隐藏 CC 组件。
和你想的一样。flag 我们就可以 放到 vuex 里。简单两句 是不是对 vuex 就有了一些概念 ?
使用 vuex 试试吧:
1、定义 数据 和 改变数据的方法 《在 store - index.js - 里定义》
2、点击时 使用 commit 调用 定义 的方法,然后把参数传过去,这里 aa 组件传的 false
3、 点击时 使用 commit 调用 定义 的方法,然后把参数传过去,这里 bb 组件传的 true
4、 cc 组件 获取 定义的数据
5、我的 测试组件都写在了 App 里,这个 随意写哪里都可以
现在看看效果:
效果 1
效果 2
还有各种调用和使用都没有讲出来。不过就上面这些就可以基本使用 vuex 了, 复杂了反而不好
我把代码 贴 出来 :
1、store - index.js 代码:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
flag: false
},
mutations: {
is_flag(state, panduan) {
state.flag = panduan
}
},
actions: {
},
modules: {
}
})
2、App 代码:
<template>
<div id="app">
<AA></AA>
<BB></BB>
<CC></CC>
<div>展示 flag 的 值: {{ getFlag }}</div>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
import AA from './components/aa.vue'
import BB from './components/bb.vue'
import CC from './components/cc.vue'
export default {
name: 'App',
components: {
AA,BB,CC
},
computed: {
getFlag () {
return this.$store.state.flag
}
}
}
</script>
<style>
</style>
3、aa 组件代码:
<template>
<div class="aa" @click="cc_flag">我是组件AA, 点击改变 CC 组件的 flag 值 为 false</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
cc_flag () {
this.$store.commit('is_flag', false)
}
}
}
</script>
<style>
.aa {
width: 200px;
height: 50px;
background-color: antiquewhite;
margin-bottom: 20px;
}
</style>
4、bb 组件代码
<template>
<div class="bb" @click="cc_flag">我是组件BB, 点击改变 CC 组件的 flag 值 为 true</div>
</template>
<script>
export default {
methods: {
cc_flag () {
this.$store.commit('is_flag', true)
}
}
}
</script>
<style>
.bb {
width: 200px;
height: 50px;;
background-color: aliceblue;
margin-bottom: 20px;
}
</style>
5、 cc组件代码:
<template>
<div class="cc" v-if="getFlag">
我时CC组件,我展示 flag 的 值: {{getFlag}}
</div>
</template>
<script>
export default {
data() {
return {}
},
computed: {
getFlag () {
return this.$store.state.flag
}
},
}
</script>
<style>
.cc {width: 300px;height: 50px;background-color: #fff;}
</style>