2017-09-23 50 views
0

我想分配數據中的道具值並在掛載中使用這個數據值。現在我的做法是不工作:如何使用掛載vue裏面的數據值js

dashboard.vue

<template> 
    <div> 
     <navigation-section :userid='userID' 
          :username='username' 
          :profilepic='profile_pic' 
          :unreads='unreads'> 
     </navigation-section> 
    </div> 
</template> 

<script> 
    import NavigationSection from '../components/NavigationSection'; 

    export default { 
     components: { 
      NavigationSection, 
     }, 

     data() { 
      return { 
       posts: [], 
       userID: '', 
       username: '', 
       unreads: [], 
       profile_pic: '', 
      } 
     }, 

     created() { 
      this.getNavInfo(); 
     }, 

     methods: { 
      getNavInfo() { 
       axios.get('get_nav_info').then(response => { 
        this.userID = response.data.userID; 
        this.username = response.data.username; 
        this.profile_pic = response.data.profile_pic; 
        this.unreads = response.data.unreads; 
       }) 
      } 
     } 
    } 
</script> 

NotificationSection(dashboard.vue兒童)

<template> 
    <div> 
     <notification :userid='userid' :unreads='unreads'></notification> 
     <h1>{{ username }}</h1>  
     <img :src='profilepic' :alt='profilepic'> 


    </div> 
</template> 

<script> 
    import Notification from '../components/Notification'; 

    export default { 
     props:['userid', 'username', 'unreads', 'profilepic'], 
     components: { 
      Notification 
     } 
    } 
</script> 

通知(NotificationSection的孩子.vue)

<template> 
    <div> 
     // values shows in template 
     unreads array length: <div class="count" v-if='unreads.length > 0'>{{ unreads.length }}</div> 
     userid : <p>{{ userid }}</p> 
    </div> 
</template> 

<script> 
    export default { 
     props:['unreads', 'userid'], 

     computed: { 
      userID() { 
       return this.userid 
      } 
     }, 

     mounted() { 
      console.log(this.userID); // ** problem : in console.log shows a blank instead of id which is working on template. 
     } 
    } 

</script> 

enter image description here

我編輯了這個問題。值顯示在模板中,但是當我想要使用內置的安裝或事件中的道具值嘗試訪問腳本內部的數據值它不工作。提前謝謝你的幫助。

+0

的問題不會出現在張貼代碼。 – Bert

+0

你是說代碼沒問題? @Bert – WahidSherief

+0

是的。這是一個例子。唯一添加的是模板。有用。 https://codepen.io/Kradek/pen/jGVPvK?editors=1010 – Bert

回答

0

您可以使用計算性能:

export default { 
    props: ['userid'], 

    computed: { 
     userID() { 
      return this.userid 
     } 
    }, 

    mounted() { 
     console.log(this.userID); 
    } 
} 

或者乾脆:

export default { 
    props: ['userid'], 

    mounted() { 
     console.log(this.userid); 
    } 
} 
+0

當我試圖訪問在安裝或創建它的ID變爲空或空白。這真的很奇怪。因爲它顯示在模板:( – WahidSherief

+0

嗯你可以更新與您的父組件模板的問題? – Ikbel

+0

我已經編輯了與父母代碼的問題,請看看。@Ikbel – WahidSherief

相關問題