优秀的编程知识分享平台

网站首页 > 技术文章 正文

简单易用的Vuex,拿来直接用就行了

nanyue 2024-09-29 15:08:38 技术文章 189 ℃

不啰嗦了,上来就看代码。(以下代码基于vue3的语法)

注意:如果你不知道vuex是个啥,请移步官网看介绍。

1、定义一个store,在项目中创建一个store目录,创建index.js文件

说明:为了便于代码维护,建议actions中的名字用小写,mutations中定义用大写

//引入vuex
import { createStore } from 'vuex'

//准备actions - 用于响应组件中的动作,通常可以进行一些复杂的异步操作
const actions = {
    //设置count值
    count_set(context, value) {
        context.commit('COUNT_SET', parseInt(value));
    },
    //count值累加
    count_add(context, value) {
        context.commit('COUNT_SET', context.state.count + parseInt(value));
    },
}

//准备mutations -  用于操作数据 (不建议做过多的业务逻辑,只对state数据做操作)
const mutations = {
    COUNT_SET(state, value) {
        state.count = value;
    },
}

//准备state - 用于操作存贮数据
//我们假设有个数据 count
const state = {
    count: 0,
}

//将state中的数据进行加工,类似于计算属性
const getters = {
    countStr(state) {
        return `值:${state.count}`;
    }
}

//创建store,暴露store
export default new createStore({
    actions,
    mutations,
    state,
    getters
});


2、main.js中引入store

import { createApp } from 'vue'
import App from './App.vue'
import store from './store';

const app = createApp(App);
app.use(store);
app.mount('#app');


3、开始开心的使用咯

来到app.vue中,写入以下代码

<template>
  <p>store中存储的 count值 : {{ count }}</p>
  <button @click="count_add_actions">测试count+10</button>
  <br />
  <button @click="count_set_actions">测试设置count为200</button>
  <br />
  <button @click="count_set_commit">Commit测试设置count为 666</button>
</template>
<script setup>
import { toRefs } from "vue";
import { useStore } from "vuex";

const { state, dispatch, commit } = useStore();
const { count } = toRefs(state);

//使用actions中的方法
const count_add_actions = () => {
  dispatch("count_add", 10);
};

const count_set_actions = () => {
  dispatch("count_set", 200);
};

//直接使用mutations中的方法(原则上不建议直接使用mutations)
const count_set_commit = () => {
  commit("COUNT_SET", 666);
};
</script>


怎么样,是不是很简单。

我们项目中有太多的组件,很多全局数据需要做到响应式更新,vuex是个不错的选择。

当然你也可以学习使用Pinia 。


最后注意看下依赖版本:

"dependencies": {
    "vue": "^3.0.4",
    "vuex": "^4.1.0"
  },

Tags:

最近发表
标签列表