vue用到了很多组件,也就是.vue文件,每一个.vue文件都是一个组件,独立作用域,可以重复使用,相当于把每个页面封装了一下,可以在不同的地方调用,现在我们在App.vue中引入两个组件:HelloWorld和Counter组件,在这两个组件中都使用到了相同的数据,我们如何保持数据的一致性,有两种方法,一种是事件总线,一种是vuex
实现是效果是单击count组件中的按钮count和helloworld组件中的值都加1
事件总线
APP.vue中代码如下
<template>
<div id="app">
<HelloWorld msg="Welcome to Your Vue.js App" />
<Counter />
</div>
</template>
<script>
//引入我们要用的插件
import HelloWorld from "./components/HelloWorld.vue";
import Counter from "./components/Counter.vue";
import { mapGetters } from "vuex";
export default {
name: "app",
//引入的插件使用需要在components中注册
components: {
HelloWorld,
Counter,
},
};
</script>
<style>
html,
body,
#app {
height: 100%;
}
#app {
display: flex;
flex-direction: column;
}
.van-tabbar--fixed {
position: static;
}
.main {
flex: 1;
overflow: auto;
}
</style>
main.js中代码如下
import Vue from "vue";
import Vuex from "vuex";
import Vant from "vant";
import "vant/lib/index.css";
import App from "./App.vue";
import store from "./store"; //保存vuex模块,每个页面的数据分块显示
import router from "./router";
Vue.use(Vuex);
Vue.use(Vant);
Vue.config.productionTip =