Vue項目中的倒計時,使用Vuex輕鬆解決(focusdroid)
—使用簡便的方法,解決繁瑣的事情!
- 爲什麼使用Vuex來寫這個倒計時插件,現在網上大多使用屬性的方法來寫Vue項目中的倒計時,但是與衆不同是我的風格。
廢話不多說,直接開幹!
直接上代碼,這個你一定懂的…
組件裏的代碼
<template>
<div id="app">
<h1>welcome Vuex2.0</h1>
//點擊倒計時開始
<input type="button" value="增加" @click="start">
<div>
還有:{{count}} 秒
</div>
</div>
</template>
<script>
import {mapActions, mapGetters} from 'vuex'
export default {
data(){
return {
temp:false
}
},
computed:mapGetters([
'count'
]),
methods:mapActions([
'start'
])
}
</script>
store裏的操作
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
var state = {
count:3,
}
const mutations = {
start(state,timer){//處理數據的變化
//處理倒計時
if(state.count != 0 ){
state.count--;
}else {
clearInterval(timer)
}
}
}
const actions ={
start:({//處理一些異步請求,判斷,流程控制
commit
}) => {
// clearInterval(timer)
var timer = setInterval(function(){
commit('start')
},1000)
}
}
const getters = {
count(state){
return state.count;
}
}
export default new Vuex.Store({
state,
actions,
mutations,
getters
})
—仔細看看這個,沒毛病