欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > vuex 简单使用

vuex 简单使用

2025/2/22 2:03:09 来源:https://blog.csdn.net/Go_ahead_forever/article/details/145702521  浏览:    关键词:vuex 简单使用

vuex 简单使用


示例:管理一个对象状态

假设我们要管理一个用户对象 user,包含 nameage 两个属性。


1. 定义 Vuex Store

store/index.js 中定义状态、mutations、actions 和 getters:

import { createStore } from 'vuex';const store = createStore({state: {user: {name: 'John Doe',age: 30}},mutations: {// 更新用户名称updateUserName(state, newName) {state.user.name = newName;},// 更新用户年龄updateUserAge(state, newAge) {state.user.age = newAge;},// 更新整个用户对象updateUser(state, newUser) {state.user = newUser;}},actions: {// 异步更新用户名称updateUserNameAsync({ commit }, newName) {setTimeout(() => {commit('updateUserName', newName);}, 1000);}},getters: {// 获取用户全名fullName(state) {return state.user.name;},// 获取用户年龄userAge(state) {return state.user.age;}}
});export default store;

2. 在组件中使用组合式 API 管理对象

在组件中,使用 useStore 钩子访问 Vuex store,并通过 computedmethods 来操作对象状态。

<template><div><h1>用户信息</h1><p>姓名: {{ fullName }}</p><p>年龄: {{ userAge }}</p><input v-model="newName" placeholder="输入新姓名" /><button @click="updateName">更新姓名</button><input v-model="newAge" placeholder="输入新年龄" type="number" /><button @click="updateAge">更新年龄</button><button @click="updateNameAsync">异步更新姓名</button></div>
</template><script>
import { computed, ref } from 'vue';
import { useStore } from 'vuex';export default {setup() {const store = useStore();// 使用 computed 获取状态const fullName = computed(() => store.getters.fullName);const userAge = computed(() => store.getters.userAge);// 使用 ref 定义输入框的绑定值const newName = ref('');const newAge = ref('');// 更新用户名称const updateName = () => {store.commit('updateUserName', newName.value);newName.value = ''; // 清空输入框};// 更新用户年龄const updateAge = () => {store.commit('updateUserAge', parseInt(newAge.value, 10));newAge.value = ''; // 清空输入框};// 异步更新用户名称const updateNameAsync = () => {store.dispatch('updateUserNameAsync', newName.value);newName.value = ''; // 清空输入框};return {fullName,userAge,newName,newAge,updateName,updateAge,updateNameAsync};}
};
</script>

3. 代码说明

  1. State:

    • state.user 是一个对象,包含 nameage 属性。
  2. Mutations:

    • updateUserName:更新用户名称。
    • updateUserAge:更新用户年龄。
    • updateUser:更新整个用户对象(如果需要一次性更新多个属性)。
  3. Actions:

    • updateUserNameAsync:模拟异步操作,1 秒后更新用户名称。
  4. Getters:

    • fullName:返回用户的全名。
    • userAge:返回用户的年龄。
  5. 组件逻辑:

    • 使用 computed 获取 Vuex 中的状态。
    • 使用 ref 绑定输入框的值。
    • 通过 commit 提交 mutations 或 dispatch 分发 actions 来更新状态。

4. 运行效果

  • 输入新姓名并点击“更新姓名”按钮,会立即更新 Vuex 中的 user.name
  • 输入新年龄并点击“更新年龄”按钮,会立即更新 Vuex 中的 user.age
  • 点击“异步更新姓名”按钮,1 秒后会更新 Vuex 中的 user.name

总结

通过这种方式,你可以轻松管理 Vuex 中的对象状态。组合式 API 提供了更灵活的方式来访问和操作 Vuex store,同时保持代码的可读性和可维护性。如果你有更复杂的需求(如嵌套对象或数组),也可以使用类似的方式管理。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词