1. 程式人生 > 程式設計 >vue中父子元件傳值,解決鉤子函式mounted只執行一次的操作

vue中父子元件傳值,解決鉤子函式mounted只執行一次的操作

因為mounted函式只會在html和模板渲染之後會載入一次,但是在子元件中只有第一次的資料顯示是正常的,所以需要再增加一個updated函式,在更新之後就可以重新進行取值載入,完成資料的正常顯示。

beforCreate(建立之前)

Created(建立之後)

beforMount(載入之前)

Mounted(載入之後)

beforUpdate(更新之前)

Updated(更新之後)

beforDestroy(銷燬之前)

Destroyed(銷燬之後)

activate(keep-alive元件啟用時呼叫)

deactivated(keep-alive元件停用時呼叫)

errorCaptured(這個元件的作用是接受子孫元件報錯是呼叫,三個引數 錯誤物件、錯誤的元件、錯誤資訊)

父元件向

子元件傳值

通過父元件傳值呼叫子元件顯示不同的資料

父元件 :conponent.vue

子元件:iconponent.vue

父元件

<template>
 <div>
   <span>父元件</span>
   <icomponent-box :id="this.id"></icomponent-box>
 </div>
</template>
<script>
//匯入子元件
import icomponent from './icomponent.vue';
export default {
 data () {
  return {
   id:12
  }
 },components:{ //用來註冊子元件的節點
   "icomponent-box": icomponent
 }
}
</script>
<style>
</style>

子元件

<template>
 <div>子元件</div>
</template>
<script>
export default {
 updated:{
   this.getComponents();
 },mounted:{
  this.getComponents();
 },data () {
  return {
  }
 },methods:{
  getComponents(){
    this.$http.get("api/getcomponents/" + this.id);
  }
 },props: ["id"] //接收父元件傳遞過來的id值
}

</script>

補充知識:Vue父子元件傳值,子元件資料只更新一次,之後更改父元件的資料,子元件不再更新

我就廢話不多說了,大家還是直接看程式碼吧~

props:{
  reportInfo:{
    type:Object,default:()=>{}
  }
},data:function(){
	return {
		cityName :' ',reportId :' ',}
}
mounted:function () {
	 var _this = this;
	 
   //初始化獲得資料,之後在watch中監聽更新
   _this.cityName = _this.reportInfo.cityName;
   _this.reportId = _this.reportInfo.reportId;   
},
watch:{
	reportInfo(newValue,oldValue) {
		var _this = this;
    _this.cityName = newValue.cityName;
    _this.reportId = newValue.reportId;
	}
}

以上這篇vue中父子元件傳值,解決鉤子函式mounted只執行一次的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。