使用vuex实现记事本
时间: 2023-12-26 11:28:02 浏览: 81
使用vuex实现记事本可以实现数据的集中管理和状态的共享。下面是一个使用vuex实现记事本的示例:
1. 首先,在项目中安装vuex:
```shell
npm install vuex --save
```
2. 创建一个store.js文件,用于定义vuex的状态和操作:
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
events: [] // 记事本事件列表
},
mutations: {
addEvent(state, event) {
state.events.push(event)
},
toggleEventStatus(state, index) {
state.events[index].completed = !state.events[index].completed
}
},
actions: {
addEvent({ commit }, event) {
commit('addEvent', event)
},
toggleEventStatus({ commit }, index) {
commit('toggleEventStatus', index)
}
},
getters: {
completedEvents: state => {
return state.events.filter(event => event.completed)
},
uncompletedEvents: state => {
return state.events.filter(event => !event.completed)
}
}
})
export default store
```
3. 在main.js中引入store.js,并将store注入到Vue实例中:
```javascript
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
```
4. 在组件中使用vuex的状态和操作:
```vue
<template>
<div>
<input v-model="newEvent" @keyup.enter="addEvent">
<ul>
<li v-for="(event, index) in uncompletedEvents" :key="index">
<input type="checkbox" v-model="event.completed" @change="toggleEventStatus(index)">
<span :class="{ completed: event.completed }">{{ event.title }}</span>
</li>
</ul>
<h2>已完成事件:</h2>
<ul>
<li v-for="(event, index) in completedEvents" :key="index">
<input type="checkbox" v-model="event.completed" @change="toggleEventStatus(index)">
<span :class="{ completed: event.completed }">{{ event.title }}</span>
</li>
</ul>
</div>
</template>
<script>
import { mapState, mapActions, mapGetters } from 'vuex'
export default {
computed: {
...mapState(['events']),
...mapGetters(['completedEvents', 'uncompletedEvents']),
},
data() {
return {
newEvent: ''
}
},
methods: {
...mapActions(['addEvent', 'toggleEventStatus'])
}
}
</script>
<style>
.completed {
text-decoration: line-through;
}
</style>
```
通过以上步骤,你就可以使用vuex实现一个简单的记事本功能了。你可以在输入框中输入事件,按回车键添加事件,勾选复选框切换事件状态。已完成的事件会显示在已完成列表中,未完成的事件会显示在未完成列表中。
阅读全文