Vue訪問加載本地Json(渲染模版數據)時遇到的坑,報undefined

Vue訪問加載本地Json時,使用模版語法會遇到的小問題

這兩天在公司作一個H5宣傳頁面,內容比較簡單。javascript


首先是經過axios得到到的json 👆html

html(部分)👇java

<section class="box3" @click="aside=true"> <img src="./assets/img/box3.png"> <div class="words"> <span class="type">{{res[2].name}}</span> <span class="type_price"><span>{{res[2].copies_coin}}</span>USDT/份</span> <span class="tips">{{res[2].copies_amount}}YCC/份</span> <span class="year">預計年化產率{{res[2].annual_yield}}%</span> <span class="fix1">預計產量</span> <span class="fix2">(YCC/天)</span> <span class="num">{{res[2].basic_yield}}</span> <span class="num_up">+{{res[2].presented_yield}}</span> </div> </section>複製代碼

Data()👇
ios

data(){
        return{
            datas:'',
            res:'',
        }
    },複製代碼

methods()👇ajax

getData(){
    let url = 'http://192.168.33.200/pre-cloud-miner.json'
    ajax(this,url,'',(response)=>{
        this.datas = eval('('+response+')');
        this.res = this.datas[90];
        console.log(this.res[0].name)
    },"GET")
}複製代碼

結果console.log顯示A090,正確,可是卻報錯:
django


神奇的是頁面正常渲染了:
json


若是把name刪掉,就會報下一個:copies_coin的錯,依次類推axios

網上查詢發現緣由是獲取本地json文件是異步操做,一開始res爲' '空字符串,因此會報res.name爲undefined。解決辦法有兩種:數組

1 . 初始定義res時,就把屬性設置好,不要作空字符串或者是空對象,空數組。bash

res:[{},{},{}], //由於後臺返回的數據格式就是這樣,這樣再刷新頁面就不會報錯了複製代碼

2 . 用v-if解決:

<div class="words" v-if="res[2]"> <span class="type">{{res[2].name}}</span> <span class="type_price"><span>{{res[2].copies_coin}}</span>USDT/份</span> <span class="tips">{{res[2].copies_amount}}YCC/份</span> <span class="year">預計年化產率{{res[2].annual_yield}}%</span> <span class="fix1">預計產量</span> <span class="fix2">(YCC/天)</span> <span class="num">{{res[2].basic_yield}}</span> <span class="num_up">+{{res[2].presented_yield}}</span> </div>複製代碼
相關文章
相關標籤/搜索