Vue3 Vuex

一、  安装

npm install vuex@next --save

二、 基本使用

store.js

import { createStore } from 'vuex'

const store = createStore({
    //用来保存数据
    state() {
        return {
            count: 2
        }
    },
    //用来改变共享的数据
    mutations: {
        increment(state) {
            state.count++
        }
    }
})

export default store

注册

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index.js'
import store from './store/store'

createApp(App).use(router).use(store).mount('#app')

使用

<template>
home
{{$store.state.count}}
<br/>
<button @click='add'>按钮</button>
</template>

<script>
export default {
   methods:{
       add(){
        this.$store.commit('increment')
       }
   }
}
</script>

在改变值的时候要通过mutation里的公共方法,而不是直接给store.state.count赋值。

 使用计算属性

<script>
export default {
    computed: {
        count() {
            return this.$store.state.count
        }
    },
}
</script>

mapState 辅助函数

??

 

Getter

Mutation

Action

Module

 

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

posted @ 2021-06-24 13:32  富坚老贼  阅读(107)  评论(0编辑  收藏  举报