在 Vue.js 中,操作通常指用于执行异步任务的方法或函数,例如从 API 获取数据、更新 Vuex(Vue 的状态管理库)中的状态或处理用户交互。动作通常在 Vuex 存储中用于封装复杂的逻辑和副作用,保持组件干净并专注于表示。
以下是如何在带有 Vuex 的 Vue.js 应用程序中定义和使用操作的基本示例:
- 在 Vuex 存储中定义一个操作:
// store.js
import { createStore } from 'vuex';
const store = createStore({
state: {
todos: []
},
mutations: {
SET_TODOS(state, todos) {
state.todos = todos;
}
},
actions: {
async fetchTodos({ commit }) {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
const data = await response.json();
commit('SET_TODOS', data);
} catch (error) {
console.error('Error fetching todos:', error);
}
}
}
});
export default store;
- 从 Vue 组件分派操作:
<template>
<div>
<button @click="fetchTodos">Fetch Todos</button>
<ul>
<li v-for="todo in todos" :key="todo.id">{{ todo.title }}</li>
</ul>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['todos'])
},
methods: {
...mapActions(['fetchTodos'])
}
};
</script>
在这个例子中:
- 我们在 Vuex 存储中定义一个操作
fetchTodos
,它进行异步 API 调用来获取待办事项,并使用突变将结果提交到存储SET_TODOS
。 - 在 Vue 组件中,我们使用
mapActions
helper 将fetchTodos
操作映射到名为 的方法fetchTodos
。然后,当单击“Fetch Todos”按钮时,我们可以在模板中调用此方法。 - 当action被调度时,它会触发store中定义的异步任务,当数据被获取并存储在Vuex状态时,组件的UI会自动更新。
Vue.js 中的操作有助于管理复杂的异步行为并保持代码库的组织性和可维护性。