Vue 父子組件傳值 props

     一、Vue 的渲染週期:javascript

      vue生命週期

                          vue 如何實現響應式追蹤。vue

                  

 

      父子組件通訊有不少方式,今天單獨聊下props 的方式。咱們經過查找官方文檔很容發現,props傳值有靜態和動態兩種傳值方式。java

                  固然props 還提供許多驗證,使數據更加嚴謹。this

                  在使用父子傳值時,出現了, 按照文檔說明,例如:spa

 

 1 <template>
 2     <div v-if="data">{{parentName}}  3         
 4         <input type="text"  v-model="parentName" />
 5     </div>
 6 </template>
 7 
 8 <script>
 9 export default { 10  props:{ 11  parentName:String 12  }, 13  data(){ 14     return { 15         data:this.parentName 16  } 17  }, 18  
19  beforeCreate(){ 20      console.log("child beforeCreate"); 21  }, 22  created(){ 23      console.log("child created"+this.parentName); 24  }, 25  mounted(){ 26      console.log("child data Mounted"+this.parentName); 27  }, 28  beforeMount(){ 29      console.log("beforeMount data"+this.parentName); 30  }, 31  beforeUpdate(){ 32      console.log("beforeUpdate data"+this.parentName) 33  } 34 
35 } 36 </script>
37 
38 <style>
39 
40 </style>

父組件引用:code

  

<template>
    <div>    <child  :parent-name="name"/>
    <input   type="text" v-model="name" />
</div>
</template>

<script>
import child from './child.vue'
export default {
   components:{
       child
   },
   data(){
       return {
           name:"asda"
       }
   },
   beforeCreate(){
       console.log("parent beforeCreate")
   },
   created(){
       console.log("parent created")
       
   },
   beforeMount(){
       console.log("parent beforeMount")
   },
   mounted(){
       console.log(" parent mounted")
        this.name="hahshdf"
   }
}
</script>

<style>

</style>

  忽然想到,這個父子組件渲染的順序如何,如上述代碼,component

  

 

     如圖所示,渲染順序是從子組件先掛載後,父組件在掛載。這個渲染順序能夠決定我什麼時候傳值,比較。blog

     從執行渲染順序來講,給子組件的props 中賦值,應該在父組件掛載前,最好是在子組件建立前即 beforeCreate 方法後,賦值。 切不可在beforeCreate 賦值,會致使未定義錯誤。生命週期

    若是在父組件掛載後,賦值會出現什麼狀況呢。事件

  沒錯,和你猜測的很對,會觸發子組件的更新事件,會致使局部在渲染。

  看文檔提示,通常的props 傳值,能夠做爲data()方法的中return的初始值使用,在做爲初始值使用時,切記

data(){
    return {
        data:this.propsValue
        }
   }

  這個是重新返回一個新值,this.propsValue 改變不會再影響data 的值。

     最後說一句,如今vue 是單向的數據流,即 改變父組件中的值,能夠影響子組件的值,可是改變子組件的值,父組件的值不變。

相關文章
相關標籤/搜索