zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Vuex4之简单使用

简单 使用
2023-09-11 14:19:18 时间

安装

npm install vuex@4 --save

或者

yarn add vuex@4 --save

简单使用

  1. src下新建store,并新建index.js文件,写上如下代码
import { createStore } from "vuex"

// 创建一个新的 store 实例
const store = createStore({
    state() {
        return {
            count: 0
        }
    },
    mutations: {
        increment(state) {
            state.count++
        }
    }
})

export default store
  1. 挂载到全局
import store from "./store"

const app = createApp(App)
app.use(store) // 挂载到全局

app.mount('#app')
  1. 在组件中的使用,我们新建一个组件,在组件中写上如下代码
<script setup>
import { toRefs } from "vue";
import {useStore} from "vuex"

const {state,commit} = useStore()

const {count} = toRefs(state)
const add = () => {
    commit("increment")
}
</script>

<template>
    <h2>{{count}}</h2>
    <button @click="add">增加</button>
</template>
  1. 运行项目在这里插入图片描述

点击之后发现在vuex中的数据也是响应式的数据