Javascript

vue3.x vuex使用

本文主要是介绍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使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!