Vuex、Pinia

Vuex 的基本使用:

安装 Vuex:

复制代码
npm install vuex --save

创建 Vuex Store:

复制代码
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    // 状态数据
  },
  mutations: {
    // 更改状态的方法
  },
  actions: {
    // 处理异步操作的方法
  },
  getters: {
    // 获取状态的方法
  }
});

export default store;

将 Vuex Store 注入到 Vue 实例中

复制代码
new Vue({
  el: '#app',
  store, // 注入 Vuex store
  render: h => h(App)
});

在组件中使用 Vuex:

复制代码
<template>
  <div>
    <p>{{ $store.state.someState }}</p>
    <button @click="updateState">Update State</button>
  </div>
</template>

<script>
export default {
  methods: {
    updateState() {
      this.$store.commit('updateSomeState', newValue);
    }
  }
}
</script>

Vuex 核心概念:

State(状态):

State 是 Vuex 中存储数据的地方。它类似于 Vue 实例中的 data 对象,但是它是全局的,可以在应用的任何组件中使用。State 可以通过 this.$store.state 来获取。

Mutation:

Mutation 是用来变更 Vuex store 中的状态的唯一方法。它们是同步函数,用于修改 state 中的数据。在组件中通过 this.$store.commit('mutationName', payload) 来触发 mutation。

如何使用 Action 函数:

Actions 用于处理异步操作或复杂逻辑,它提交 mutation 来变更状态。在组件中通过 this.$store.dispatch('actionName', payload) 来触发 action。

复制代码
actions: {
  fetchData({ commit }) {
    axios.get('api/data')
      .then(response => {
        commit('updateData', response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }
}

如何使用 Getter 函数:

Getter 用于从 store 中派生出一些状态,类似于组件中的计算属性。Getter 接收 state 作为参数,可以接受其他 getters 作为第二个参数。在组件中通过 this.$store.getters.getterName 来获取 getter。

复制代码
getters: {
  // Getter 函数定义
  doneTodos: state => {
    return state.todos.filter(todo => todo.done);
  }
}

// 在组件中使用 Getter
computed: {
  doneTodos() {
    return this.$store.getters.doneTodos;
  }
}

Vuex Store 的使用:

创建 Store:
复制代码
import { createStore } from 'vuex';

const store = createStore({
  state: {
    // 状态数据
  },
  mutations: {
    // 更改状态的方法
  },
  actions: {
    // 处理异步操作的方法
  },
  getters: {
    // 获取状态的方法
  }
});

export default store;
注入到 Vue 应用中:
复制代码
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';

const app = createApp(App);
app.use(store); // 注入 Vuex store
app.mount('#app');
在组件中使用:
复制代码
<template>
  <div>
    <p>{{ $store.state.someState }}</p>
    <button @click="updateState">Update State</button>
  </div>
</template>

<script>
import { useStore } from 'vuex';

export default {
  setup() {
    const store = useStore();

    const updateState = () => {
      store.commit('updateSomeState', newValue);
    };

    return {
      updateState
    };
  }
}
</script>

Pinia 核心概念:

State(状态):

State 是 Pinia 中存储数据的地方,它类似于 Vuex 中的 state。State 可以通过 useStore() 来获取。

Getter(获取器):

Getter 用于从 state 中派生出一些状态,类似于 Vuex 中的 getters。Getter 可以通过 useStore().getters.getterName 来获取。

Action(动作):

Action 用于处理异步操作或复杂逻辑,类似于 Vuex 中的 actions。Action 可以通过 useStore().yourActionName() 来调用。

Pinia 和 Vuex 的比较:

Pinia 和 Vuex 都是 Vue.js 应用程序的状态管理库,但它们在一些方面有所不同。

  • API 设计:Pinia 使用了基于函数的 API,而 Vuex 使用了对象风格的 API。
  • 类型支持:Pinia 更好地支持 TypeScript,并提供了更好的类型推断。
  • 模块化:Pinia 支持模块化管理状态,而 Vuex 需要使用额外的插件才能实现类似的功能。
  • 性能:Pinia 在某些情况下可能具有更好的性能,因为它使用了更现代的技术。
相关推荐
deli00711 分钟前
1 个汉字算几个 token?实测中英文 prompt 与代码的编码差异
前端
无限聚核17 分钟前
抖音 certificate.prepare 之后怎么验券?和美团 msconsume 差在哪,无限聚核
前端·微信小程序
2603_9658966227 分钟前
Grid 网格布局|CSS 二维页面排版体系
前端·css
有味道的男人42 分钟前
搜好货平台关键词商品搜索接口:分页容错与商品数据轻量化提取方案
服务器·前端·javascript
lovingsoft1 小时前
Chrome Lighthouse 详解
前端·chrome
Qlly2 小时前
全栈工程师怎么接需求?从一句「加个功能」聊到能开发、能验收
前端·后端
马可家的菠萝2 小时前
你的微信“文件传输助手”,是不是已经成了第二个网盘?
前端·后端·架构
略略略啦2 小时前
Vibe Coding 基于Spec DD和TDD的实践指南
前端
shmily麻瓜小菜鸡2 小时前
前端实现图片与PDF文字识别敏感信息打码方案
前端·pdf·状态模式
打工仔折腾 AI2 小时前
LangChain 工具调用实战:从 Tool 定义到 Agent 执行链路拆解
java·前端·人工智能·后端·python·langchain·ai agent 实战