vue3.x vuex使用
Posted 天行子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue3.x vuex使用相关的知识,希望对你有一定的参考价值。
安装vuex
npm install vuex@next --save-dev
vuex简单使用
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>
浏览器显示效果
以上是关于vue3.x vuex使用的主要内容,如果未能解决你的问题,请参考以下文章
Vue3.x 从零开始—— Router + Vuex + TypeScript 实战演练(上)