2017-07-27 80 views
1

我想知道如果道具來自後端的響應,什麼是處理Vue.js道具的正確方法?什麼是正確的方式來處理Vue.js道具從後端的響應

好吧,讓我們說,孩子組件具有prop稱爲person。一個name是人的對象。

<template> 
     {{ person.name }} 
    <template> 

    <script> 
    export default { 
     name: 'ChildComponent', 
     props:['person'], 
     created(){ 
      this.getName(); 
     }, 
     data(){return{name:''}}, 
     methods:{ 
      getName(){ 
      this.name = this.person.name; 
      } 
    } 

    </script> 

父組件是這樣

<template> 
     <ChildComponent :person="person"></ChildComponent> 
    <template> 

    <script> 
    export default { 
     name: 'ParentComponent', 
     created(){ 
      this.getPerson(); 
     } 
     data(){ 
      return { 
      person: null 
      } 
     }, 
     methods:{getPerson(){ 
      // send request to server or api then update name 
      sendrequest().then(person => { this.person = person}); 
     }} 
    </script> 

起初,之前得到的迴應,會有一個警告can't get name from person。 我知道2層的方法來處理這個問題:

  1. <ChildComponent :person="person" v-if="person"></ChildComponent>
  2. 手錶person支撐在,每個人改變時,重新運行childcomponent的getName()方法或設置名稱作爲計算屬性。

因此,這裏的問題再一次,他們在處理這個正確的方法是什麼?還有其他一些方法,如使用Vuex?

Thx

回答

0

這不是vue警告。基本上,這是JavaScript錯誤TypeError: Cannot read property 'name' of null,這VUE可以顯示你的警告。你的1變種是okey。同<div v-if="person">{{person.name}}</div>在你的孩子。你也可以用一些東西填滿你的人喜歡

return { 
    person: {name: 'loading...'} 
} 

,並在您的父母

mounted: function() { 
    // your person will be loaded when component mounted 
    this.getPerson() 
} 
1

這真的取決於你的使用情況,如果你不希望顯示的人,直到它已準備就緒然後v-if似乎是一個正確的路要走。

如果你想顯示的東西,直到人物對象是準備好你有2種選擇:

  1. 給人默認名稱,或用空的名字初始化它
  2. 顯示加載組件,直到人準備好
相關問題