前端相關

Vue3 報錯 “[Vue warn]: Property “xxx” was accessed during render but is not defined on instance.” 解決方法之一

vue warn 情況

[Vue warn]: Property was accessed during render but is not defined on instance.

被報錯的情況

從Vue2重構至Vue3時報錯,vue2時有報錯但仍可運行;vue3報錯並阻擋運行。
*因為專案關係不能使用async/await語法。
父元件

//template
<div class="content">
  <childrenComponent
  :listData = "listData"
  />
</div>
//script
export default {
  name:"parentComponent",
  components:{
    childrenComponent,
  },
  data() {
    return {
      listData: [ ],
  },
created(){
 initData();
},
  methods:{
    initData(){
    this.axios.get("/api/citycafe/list").then(res => {
        console.log('citycafe',res.data);
        if(res.data.array.length !== 0){
          this.list_citycafe = res.data.array;
        }
      })
      .catch(err=>{
        console.log("錯誤",err);
      });
    }
  }
}

子元件 childrenComponent.vue

//template
<div class="content">
  {{ listData[0].name }}
</div>
//script
export default {
  name:"childrenComponent",
  props:["listData"],
}

出現報錯

更正後的情況

判斷:應該是因為call api抓到資料前,子元件生成卻沒有抓到資料,所以設一個v-if判斷,抓到資料後再渲染元件。

父元件

//template
<div class="content" v-if="!isLoading">
  <childrenComponent
  :listData = "listData"
  />
</div>
//script
export default {
  name:"parentComponent",
  components:{
    childrenComponent,
  },
  data() {
    return {
      isLoading: true,
      listData: [ ],
  },
created(){
 initData();
},
  methods:{
    initData(){
    this.axios.get("/api/citycafe/list").then(res => {
        console.log('citycafe',res.data);
        //判斷的條件也可以改成要渲染的陣列長度是否為0。
        if(res.data.array.length !== 0){ 
          this.list_citycafe = res.data.array;
          this.isLoading = false;
        }
      })
      .catch(err=>{
        console.log("錯誤",err);
      });
    }
  }
}

子元件 childrenComponent.vue

//template
<div class="content">
  {{ listData[0].name }}
</div>
//script
export default {
  name:"childrenComponent",
  props:["listData"],
}
Yuki Hiew

Recent Posts

KKDAY 八月國內/海外/銀行優惠折扣碼 2024

嗨各位,YUKI來分享熱騰騰的...

2 個月 ago

釜山西面站美食~ 螞蟻家辣炒章魚 24hr營業

位於釜山西面站附近的 螞蟻家辣...

11 個月 ago

This website uses cookies.