示例
安装最新版Vuex
npm install --save vuex@next
在main.js中配置vuex
import { createApp } from 'vue';
import { createStore } from 'vuex';
import App from './App.vue';
const store = createStore({
state() {
return {
counter: 0,
};
},
});
const app = createApp(App);
app.use(store);
app.mount('#app');
在App.vue中使用
<template>
<base-container title="Vuex">
<h3>{{$store.state.counter }}</h3>
<button>Add 1</button>
</base-container>
</template>
<script>
import BaseContainer from './components/BaseContainer.vue';
export default {
components: {
BaseContainer,
},
};
</script>
<style>
* {
box-sizing: border-box;
}
html {
font-family: sans-serif;
}
body {
margin: 0;
}
</style>
组件BaseContainer.vue
<template>
<section>
<h2>{{ title }}</h2>
<slot></slot>
</section>
</template>
<script>
export default {
props: ['title'],
};
</script>
<style scoped>
section {
max-width: 30rem;
margin: 2rem auto;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.26);
padding: 1rem;
}
h2 {
text-align: center;
}
</style>