网络编程
位置:首页>> 网络编程>> JavaScript>> vue中父子组件传值,解决钩子函数mounted只运行一次的操作

vue中父子组件传值,解决钩子函数mounted只运行一次的操作

作者:醉醉美丽栗子  发布时间:2024-05-09 15:26:31 

标签: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;
}
}

来源:https://blog.csdn.net/qq_39990827/article/details/91982721

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com