vue初始化出现undefined的问题

1、使用vue初始化下拉列表的时候,需要动态获取数据库的列表数据,因此在初始化的时候需要异步加载数据。但是往往会报undefined的错。因为渲染在异步加载之前,导致渲染的时候还没有获取到相对于的数据,导致报undefined的错误。

 

 处理办法就是初始化的时候加一个判断即可。

附上代码:(加了一个v-if="locationArray!=''"的判断)

<template>
    <view class="picker-border">
        <view class="uni-title uni-common-pl">请选择仓库</view>
        <view class="uni-list">
            <view class="uni-list-cell">
                <view class="uni-list-cell-left">
                    当前仓库
                </view>
                <view class="uni-list-cell-db" v-if="locationArray!=''">
                    <picker @change="bindPickerChange" :value="index" :range="locationArray">
                        <view class="uni-input">{{locationArray[index].LOCATION_DESC}}</view>
                    </picker>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                index: 0,
                locationArray:''
            }
        },
        methods:{
            bindPickerChange: function(e) {
                console.log('picker发送选择改变,携带值为', e.target.value)
                this.index = e.target.value
            },
            // 获取仓库信息
            getLocation(){
                uni.request({
                    url: this.$common.url+"LoginApi/getLocation", 
                    data: {},
                    success: (res) => {
                        if(res.data.status==false){
                            uni.showModal({
                                title: '错误',
                                content: res.data.errMessage,
                                showCancel:false
                            });
                        }else{
                            this.locationArray=res.data;
                            console.log(this.locationArray)
                        }
                    },
                    fail:(err)=>{
                        uni.showModal({
                            title: '错误',
                            content: '获取仓库信息失败!'+err,
                            showCancel:false
                        });
                    }
                });
            },
            onLoad() {
                this.getLocation()
            }
        }
    }
</script>

<style>
    .picker-border{
        border: 1rpx #0A98D5 solid;
    }
</style>

参考:https://www.cnblogs.com/huancheng/p/9188287.html

posted @ 2021-01-16 10:42  masha2017  阅读(6401)  评论(0编辑  收藏  举报