npm install vuex@next --save-dev
store.js
import { createStore } from 'vuex' // 创建一个新的 store 实例 const store = createStore({ state () { return { count: 1 } } }); export default store;
main.js
import { createApp } from 'vue' import App from './App.vue' import store from './store' createApp(App).use(store).mount('#app');
App.vue
<template> <div id="app"> <Component1></Component1> <Component2></Component2> </div> </template> <script> import Component1 from './components/Component1' import Component2 from './components/Component2' export default { name: 'App', components:{ Component1, Component2 } } </script> <style scoped> </style>
components/Component1.vue
<template> <div> <h3>我是组件1</h3> <span>store.state.count</span> <button @click="add">组件1-自增</button> {{store.state.count}} </div> </template> <script> import {useStore} from 'vuex' export default { name: "Component1", data(){ return { title: '组件1-title' } }, setup:function(){ const store = new useStore(); return { store } }, methods:{ add:function () { this.store.state.count++; } } } </script> <style scoped> </style>
components/Component2.vue
<template> <div> <h3>我是组件2</h3> <span>store.state.count</span> <button @click="add">组件2-自增</button> {{store.state.count}} </div> </template> <script> import {useStore} from 'vuex' export default { name: "Component2", data(){ return { title: '组件2-title' } }, setup:function(){ const store = new useStore(); return { store } }, methods:{ add:function () { this.store.state.count++; } } } </script> <style scoped> </style>
浏览器显示效果