文章加密

;

2019年4月24日 星期三

promise 及 Vue访问本地json时会出现TypeError: Cannot read property '0' of undefined

https://www.cnblogs.com/zhuzhenwei918/p/6915451.html   vue中promise的使用

https://segmentfault.com/a/1190000016680014   vue+axios+promise实际开发用法

https://www.youtube.com/watch?v=s6SH72uAn3Q

前因(問題)
Vue访问本地json时会出现TypeError: Cannot read property '0' of undefined


正解
在JSON请求回来的时候已经渲染页面了,此时你给的page3的默认值是[],所以page3.page3_aundefined,你再使用[0]当然就会报错了,你需要在初始化data的时候,把需要的结构都初始化,代码如下:
data: function() {
    return {
        page3: {
            page3_a: [{
                title: []
            }]
        }
    }
}
这样在数据没有回来的时候访问page3.page3_a[0].title才不会报错。



或是

index_content:{
                    announce:[{
                        info:''
                    }],
                    footer_image:[{
                        info:''
                    }],
                    footer_text:[{
                        info:''
                    }],
                    ftd_text:[{
                        info:''
                    }],
                    image:[{
                        info:''
                    },{
                        info:''
                    },{
                        info:'' //就是這個啦!
                    }],
                }

這樣index_content.image[2].info就不會出錯誤訊息!


※結果搜出promise順便了解下
可以快速理解的例子
const promise = new Promise((resolve, reject) => {
setTimeout(() =>{
const r =Math.random();
if(r >0.5){
resolve(r)
}else{
reject(r)
}
},1000)
})

promise.then((value) => {
console.log('成功',value)
}).catch((error) => {
console.log('失敗', error)
})


基础篇
let promiseToCleanTheRoom = new Promise(function(resolve, reject) {

  //cleaning the room

  let isClean = false;

  if (isClean) {
    resolve('Clean');
  } else {
    reject('not Clean');
  }

});

promiseToCleanTheRoom.then(function(fromResolve) {
  console.log('the room is' + fromResolve);
}).catch(function(fromReject){
console.log('the room is' + fromReject);
})


//结果:the room is not Clean


复杂篇
let cleanRoom = function() {
  return new Promise(function(resolve, reject) {
    resolve('Cleaned The Room');
  });
};

let removeGarbage = function(message) {
  return new Promise(function(resolve, reject) {
    resolve(message + ' remove Garbage');
  });
};

let winIcecream = function(message) {
  return new Promise(function(resolve, reject) {
    resolve( message + ' won Icecream');
  });
};

cleanRoom().then(function(result){
return removeGarbage(result);
}).then(function(result){
return winIcecream(result);
}).then(function(result){
console.log('finished ' + result);
})

//结果:finished Cleaned The Room remove Garbage won Icecream

进阶篇
阵列里全部执行完才触发
Promise.all ( [ cleanRoom(), removeGarbage(), winIcecream() ] ).then(funtion(){
    console.log('all finished!')
})

阵列里只要有一个执行完就触发(例如接收同样的data,只要拿到一个就可以往后执行)
Promise.race ( [ cleanRoom(), removeGarbage(), winIcecream() ] ).then(funtion(){
    console.log('one of them is finished')
})

沒有留言:

張貼留言