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 在某些情况下可能具有更好的性能,因为它使用了更现代的技术。
相关推荐
bugcome_com2 小时前
JWT 知识小课堂:从入门到精通,一文吃透 JSON Web Token
前端·json
To_OC3 小时前
写了三天 Next.js,我的 React 世界观被拆了又装回去
前端·全栈·next.js
独泪了无痕3 小时前
viewer.js 安装与配置指南:实现图片预览功能
前端·vue.js
起床学FPGA5 小时前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
Fluxart.ai5 小时前
电商商品图审核怎么自动化?规则引擎、人工复核与发布门禁
java·前端·自动化
why技术5 小时前
AI 写的文章,可能都带着手敲一遍都去不掉的“隐形水印”。
前端·人工智能·后端
愚公搬代码6 小时前
【愚公系列】《Android应用案例开发大全》016-LBS类应用掌上杭州(辅助工具类的开发)
android·前端
CodeSheep6 小时前
又一个华为天才少年,离职了!
前端·后端·程序员
kyriewen6 小时前
面试官说"打开你的AI工具"——我才发现,他考的根本不是写代码
前端·人工智能·面试
IT_陈寒7 小时前
Vue的双向绑定把我坑惨了,原来这个场景不能用
前端·人工智能·后端