vuex实现todolist
时间: 2023-07-08 18:46:41 浏览: 102
Vue实现ToDoList
好的,下面是一个简单的使用Vuex实现TodoList的示例代码:
首先,需要安装Vuex:
```
npm install vuex --save
```
然后,创建一个store.js文件,用于定义Vuex的状态、mutations、actions等:
```javascript
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '学习Vue', completed: false },
{ id: 2, text: '学习Vuex', completed: false },
{ id: 3, text: '学习Vue Router', completed: false }
]
},
mutations: {
addTodo (state, payload) {
state.todos.push({
id: Date.now(),
text: payload.text,
completed: false
});
},
toggleTodo (state, payload) {
const todo = state.todos.find(todo => todo.id === payload.id);
todo.completed = !todo.completed;
},
deleteTodo (state, payload) {
state.todos = state.todos.filter(todo => todo.id !== payload.id);
}
},
actions: {
addTodo ({ commit }, payload) {
commit('addTodo', payload);
},
toggleTodo ({ commit }, payload) {
commit('toggleTodo', payload);
},
deleteTodo ({ commit }, payload) {
commit('deleteTodo', payload);
}
}
});
export default store;
```
在上面的代码中,我们定义了一个todos数组作为状态,然后定义了三个mutations来修改这个状态。addTodo用于添加一个todo项,toggleTodo用于切换一个todo项的完成状态,deleteTodo用于删除一个todo项。最后,我们定义了三个actions,这些actions用于触发mutations来修改状态。
接下来,我们可以在组件中使用Vuex:
```vue
<template>
<div>
<h2>TodoList</h2>
<form @submit.prevent="addTodo">
<input type="text" v-model="newTodoText">
<button type="submit">Add Todo</button>
</form>
<ul>
<li v-for="todo in todos" :key="todo.id" :class="{ completed: todo.completed }">
<input type="checkbox" v-model="todo.completed" @change="toggleTodo(todo)">
<span>{{ todo.text }}</span>
<button @click="deleteTodo(todo)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['todos']),
newTodoText: {
get () {
return '';
},
set (value) {
this.$data.newTodoText = value;
}
}
},
methods: {
...mapActions(['addTodo', 'toggleTodo', 'deleteTodo'])
}
};
</script>
```
在上面的代码中,我们使用了Vuex提供的mapState和mapActions辅助函数,来将todos状态和addTodo、toggleTodo、deleteTodo等actions映射到组件的computed和methods中。
最后,在组件的created钩子中,我们可以使用Vuex的actions来初始化状态:
```javascript
import store from './store';
export default {
created () {
this.$store.dispatch('addTodo', { text: '学习Vuex' });
this.$store.dispatch('addTodo', { text: '学习Vue Router' });
},
store
};
```
以上就是使用Vuex实现TodoList的示例代码。
阅读全文