运用vuex的相关知识,实现计时器操作,要求如下: (1)使用actions实现异步操作,点击“计数”,计数延迟一秒加1 (2) 点击“更改计数起始数为考生学号后两位”使用store.replaceState()更改计数起始数为考生学号后两位 (3)在页面最上方写上自己的姓名学号
时间: 2023-11-22 12:55:41 浏览: 67
简化复杂的Vuex操作并在您的应用中实现快速安全的异步路由
首先,在store中定义state、mutations、actions、getters:
```
// store.js
const state = {
count: 0
}
const mutations = {
increment(state) {
state.count++
},
replaceState(state, payload) {
state.count = payload
}
}
const actions = {
async incrementAsync({ commit }) {
await new Promise(resolve => setTimeout(resolve, 1000))
commit('increment')
}
}
const getters = {
getCount: state => state.count
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
```
然后在组件中使用计时器:
```
<template>
<div>
<div>{{ name }} - {{ id }}</div>
<div>计数:{{ count }}</div>
<button @click="incrementAsync">计数</button>
<button @click="replaceState">更改计数起始数为考生学号后两位</button>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters(['getCount']),
name() {
return '姓名'
},
id() {
return '学号'
}
},
methods: {
...mapActions(['incrementAsync']),
replaceState() {
const payload = parseInt(this.id.slice(-2))
this.$store.replaceState({ count: payload })
}
}
}
</script>
```
点击“计数”按钮,触发incrementAsync action,计数延迟一秒加1;点击“更改计数起始数为考生学号后两位”按钮,触发replaceState mutation,更改计数起始数为考生学号后两位。同时,在页面最上方显示自己的姓名和学号。
阅读全文