vue——数据已更新但视图一直不渲染

想实现的效果

请求接口获取待办数目和链接,当数目>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>
原文地址:https://www.cnblogs.com/linjiangxian/p/14378051.html