添加一个新的组件TheCounter.vue
<template>
<h3>{{ counter }}</h3>
</template>
<script>
export default {
computed: {
counter() {
return this.$store.state.counter;
},
},
};
</script>
并在App.vue中使用
<template>
<base-container title="Vuex">
<!-- <h3>{{counter }}</h3> -->
<the-counter></the-counter>
<button @click="addOne">Add 1</button>
</base-container>
</template>
<script>
import BaseContainer from './components/BaseContainer.vue';
import TheCounter from './components/TheCounter.vue';
export default {
components: {
BaseContainer,
TheCounter
},
computed: {
counter() {
return this.$store.state.counter;
}
},
methods: {
addOne() {
this.$store.state.counter += 1;
}
}
};
</script>
<style>
* {
box-sizing: border-box;
}
html {
font-family: sans-serif;
}
body {
margin: 0;
}
</style>
可见main.js中的变量counter: 0,,所有组件都可以使用。