案例:当我们在App.vue中给全页面注入一个NavBar组件,然后我们有两个页面Home和About;比如说我们想在这两个页面调用这个组件的某个方法,是不能通过ref去调用的,此时我们就可以使用vuex进行通讯。
具体方法如下:
已给出源码方便大家调试。
App.vue
<template>
<div id="app">
<NavBar/>
<router-view/>
<nav>
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</nav>
</div>
</template>
<script>
// @ is an alias to /src
import NavBarfrom '@/components/NavBar.vue'
export default {
components: {
NavBar
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
NavBar.vue
<template>
<div class="index_wrap">
<div>公共组件</div>
<div class="wrap" v-if="start">
<div class="item">
<div class="btn">
<button @click="start = false">关闭弹窗</button>
</div>
<hr>
这是一个弹窗
</div>
</div>
</div>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
name: "",
data() {
return {
start: false
}
},
watch: {
trigger(star) {
if (star) {
this.start = star
this.CHANGE_TXT(false)
}
}
},
computed: {
trigger() {
return this.$store.state.status;
},
},
methods: {
...mapMutations(['CHANGE_TXT']),
}
}
</script>
<style scoped>
.index_wrap {
width: 100%;
height: 100px;
background-color: #eee;
}
.wrap {
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, .3);
position: absolute;
}
.item {
width: 500px;
height: 300px;
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: left;
}
.btn {
text-align: right;
}
</style>
当然还有vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
status: false,
},
getters: {
},
mutations: {
CHANGE_TXT(state, status) {
state.status = status
}
},
actions: {
},
modules: {
}
})
然后在Home和About页面中我们只需要通过按钮触发这段代码就可以了:
this.$store.commit("CHANGE_TXT", true)