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 在某些情况下可能具有更好的性能,因为它使用了更现代的技术。