Vue不斷請求數據 用定時器SetTimeOut
不帶參數發給后端
<template>
<div>
<el-button @click="getData">點擊</el-button>
<div>{{one}}</div>
</div>
</template>
<script>
export default {
data () {
return {
one: {}
}
},
created () {
this.getData()
},
methods: {
async getData () {
const { data: res } = await this.$http.get('/data01')
console.log(res)
this.one = res
console.log(this.one)
},
// 定時器
timer () {
return setTimeout(() => {
this.getDataone()
}, 1000)
}
},
watch: {
// watch就是用來監控數據變化,只有變化了才會調用定時器的變化
one () {
// 調用定時器
this.timer()
}
},
// 頁面銷毀后 停止計時器
destroyed () {
clearTimeout(this.timer)
}
}
</script>
帶參數發給后端
<template>
<div>
<el-button @click="getData">帶參數發送</el-button>
</div>
</template>
<script>
export default {
data () {
return {
fourData: [],
fourParams: ['Simulator.cemsSO2.anshui', 'Simulator.cemsSO2.humidity', 'Simulator.cemsSO2.shs', 'Simulator.cemsSO2.soot']
}
},
created () {
this.getData()
},
methods: {
async getData() {
const { data: res } = await this.$http.post('/index/test', this.fourParams)
console.log(res)
this.one = res
},
// 定時器
timer () {
return setTimeout(() => {
this.getData()
}, 1000)
}
},
watch: {
fourData() {
this.timer()
}
},
destroyed () {
clearTimeout(this.timer)
}
}
</script>