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 在某些情况下可能具有更好的性能,因为它使用了更现代的技术。
相关推荐
Eloudy1 小时前
ReAct 原理简介
前端·javascript·人工智能·react.js·agent·gpu
ZJU_统一阿萨姆2 小时前
【DSH】如何将 DeepSeek Harness 嵌入生产环境?万字解构 DeepSeek Agent Harness 的运行机制与安全边界
前端·javascript·安全
用户921080262862 小时前
4. 前端地图大量点位实时更新优化:后端推增量,前端做 diff
前端
SoaringHeart3 小时前
Flutter最佳实践:Web项目中文字体首次加载乱码问题解决
前端·flutter
西安小哥3 小时前
破局与重生:大厂前端如何借力 AI 转型“超级全栈“
前端·人工智能
sunly_4 小时前
TypeScript总结:16、面向对象速查
前端·javascript·typescript
张元清4 小时前
React useInterval Hook:没有过期闭包的 setInterval (2026)
javascript·react.js
MXN_小南学前端4 小时前
React超长文本域中实现“返回顶部”浮动按钮
前端·javascript·react.js
学习嵌入式的小周4 小时前
Notepad++8.8.7下载安装(附安装包)
前端·notepad++
gs801404 小时前
解构 Cordis:面向“时空可组合性”的 TypeScript 元框架深度剖析
前端·javascript·typescript