编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

一起学Vue:状态管理(Vuex) vue中的状态管理

wxchong 2024-12-25 16:08:00 开源技术 21 ℃ 0 评论

前言

要学习Vuex就要先知道这里的路由是什么?为什么我们不能像原来一样直接用标签编写链接哪?vue-router如何使用?常见路由操作有哪些?等等这些问题,就是本篇要探讨的主要问题。


Vuex是什么

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

State:类似与单组件中的data ()。

Getter:像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

Mutation:状态只能通过mutation修改,mutation是同步的。

Action:Action 提交的是 mutation,而不是直接变更状态。Action是异步操作。

Module:Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块


如何使用Vuex

首先,安装Vuex


npm install Vuex

接下来,创建一个 store。创建过程直截了当——仅需要提供一个初始 state 对象和一些 mutation:


setTodos() {
    const url = "https://localhost:44399/api/todo?pageIndex=1&pageSize=100";
    axios.get(url)
        .then((response) => {
            console.log(response);
            if (response.data.Code === 0) {
                this.Todos = response.data.Result;
            }
        });
},

接下来,在main.js文件中引入store/index.js文件:


createTodo(item) {
    const url = "https://localhost:44399/api/todo";
    axios.post(url, item)
        .then((response) => {
            console.log(response);
            if (response.data.Code === 0) {
                this.setTodos();
            }
        });
    this.selectedIndex = -1;
    this.selectedItem = {};
    this.addDialogVisible = false;
},

最后,新建一个组件TodoListWithVuex.vue


updateTodo(item) {
    const url = `https://localhost:44399/api/todo/${item.Id}`;
    axios.put(url, item)
        .then((response) => {
            console.log(response);
            if (response.data.Code === 0) {
                this.setTodos();
            }
        });
    this.selectedIndex = -1;
    this.selectedItem = {};
    this.editDialogVisible = false;
},


小结

目前为止,我们完成了Vuex的基本用法,Vuex主要管理多组件状态的共享,如果只是单个组件交互及父子组件交互应该是没有必要使用的。

文中用到的代码我们放在:https://github.com/zcqiand/miscellaneous/tree/master/vue

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表