vuex实现todolist
时间: 2023-07-08 16:46:51 浏览: 83
好的,下面是一个简单的todolist示例,使用Vuex实现状态管理:
1. 安装vuex
```
npm install vuex --save
```
2. 创建store.js文件,并在其中定义state、mutations、actions和getters
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
todoList: []
}
const mutations = {
addTodo (state, todo) {
state.todoList.push(todo)
},
deleteTodo (state, todo) {
const index = state.todoList.indexOf(todo)
state.todoList.splice(index, 1)
},
updateTodo (state, { todo, text }) {
todo.text = text
},
completeTodo (state, todo) {
todo.completed = !todo.completed
},
clearCompletedTodos (state) {
state.todoList = state.todoList.filter(todo => !todo.completed)
}
}
const actions = {
addTodo ({ commit }, text) {
commit('addTodo', {
text: text,
completed: false
})
},
deleteTodo ({ commit }, todo) {
commit('deleteTodo', todo)
},
updateTodo ({ commit }, { todo, text }) {
commit('updateTodo', { todo, text })
},
completeTodo ({ commit }, todo) {
commit('completeTodo', todo)
},
clearCompletedTodos ({ commit }) {
commit('clearCompletedTodos')
}
}
const getters = {
completedTodos: state =>
state.todoList.filter(todo => todo.completed),
activeTodos: state =>
state.todoList.filter(todo => !todo.completed)
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
```
3. 在main.js中引入store.js,并将其注入到Vue实例中
```javascript
import Vue from 'vue'
import App from './App.vue'
import store from './store.js'
new Vue({
el: '#app',
store,
render: h => h(App)
})
```
4. 在组件中使用store
```javascript
<template>
<div>
<input v-model="newTodoText" @keyup.enter="addNewTodo">
<ul>
<li v-for="todo in todos" :key="todo.id">
<input type="checkbox" v-model="todo.completed" @change="completeTodo(todo)">
<input type="text" v-model="todo.text" @blur="updateTodoText(todo)" :disabled="todo.completed">
<button @click="deleteTodo(todo)">Delete</button>
</li>
</ul>
<button @click="clearCompletedTodos">Clear Completed</button>
</div>
</template>
<script>
export default {
computed: {
todos () {
return this.$store.state.todoList
}
},
methods: {
addNewTodo () {
if (!this.newTodoText) return
this.$store.dispatch('addTodo', this.newTodoText)
this.newTodoText = ''
},
deleteTodo (todo) {
this.$store.dispatch('deleteTodo', todo)
},
updateTodoText (todo) {
this.$store.dispatch('updateTodo', { todo, text: todo.text })
},
completeTodo (todo) {
this.$store.dispatch('completeTodo', todo)
},
clearCompletedTodos () {
this.$store.dispatch('clearCompletedTodos')
}
},
data () {
return {
newTodoText: ''
}
}
}
</script>
```
以上就是一个简单的使用Vuex实现todolist的示例。
阅读全文