想實現的效果
請求接口獲取待辦數目和鏈接,當數目>0時,點擊數目跳轉鏈接。
出現的問題
頁面上待辦數目為0,但是打印彈窗發現待辦數目為1,點擊頁面上顯示的0仍可以跳轉鏈接
原因
在請求待辦時,我還請求了列表。但是列表返回的數據是null,頁面上又判斷了列表的長度。造成了瀏覽器報錯,所以就沒有再繼續渲染
代碼
<template>
<div>
<p @click="toLink(count,url)">待辦數目:{{count}}</p>
<div v-if="list.length">
<p v-for="(item,index) in list" :key="index">
列表{{item}}
</p>
</div>
</div>
</template>
<script>
import API from '../api'
export default {
data() {
return {
count: 0,
url: '',
list: []
}
},
mounted() {
const that = this
that.getNum()
that.getList()
},
methods: {
getNum() {
const that = this
const timestamp = new Date().getTime()
that.$get(API.num + '?t=' + timestamp).then(res => {
if (res.code === 200) {
const _data = res.data // 最好改為 cons _data = res.data || {}
that.count = _data.count // 最好改為 that.count = _data.count || 0
that.url = _data.url // 最好改為 that.url = _data.url || ''
}
})
},
toLink(num, url) {
if (parseInt(num) > 0) {
window.open(url)
}
},
getList() {
const that = this
const timestamp = new Date().getTime()
that.$get(API.list + '?t=' + timestamp).then(res => {
if (res.code === 200) {
that.list = res.data // <== 出現問題的地方 應改為 that.list = res.data || [] 避免返回null或undefined的情況
}
})
}
}
}
</script>
