this.$refs获取不到子组件

如下所示:

<swiper
	:style="{ height: listHeight + 'px' }"
	:current="tabIndex"
	:duration="1000"
	@change="onswiperchange"
	@transition="onswiperscroll"
	@animationfinish="animationfinish"
>
	<swiper-item class="swiper-item" v-for="(page, index1) in tabList" :key="index1">
        //子组件
		<news-item class="page-item" :lmid="page.id" ref="page"></news-item>
	</swiper-item>
</swiper>
	onReady() {
		console.log(this.$refs, this.$refs.page);
	}

打印结果:

 

原因:

关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 - 它们还不存在!$refs 也不是响应式的,因此你不应该试图用它在模板中做数据绑定。

解决:

为了在数据变化之后等待 Vue 完成更新 DOM,可以在数据变化之后立即使用 Vue.nextTick(callback)。这样回调函数将在 DOM 更新完成后被调用

解决1:官网:异步更新队列

 

解决2:

mounted:在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。

一般在mounted生命周期中,html已经渲染出,可获取this.$refs

setTimeout(() => {
    this.message = '已更新'
    console.log(this.$el.textContent) // => '未更新'
    this.$nextTick(function () {
      console.log(this.$el.textContent) // => '已更新'
    })
},0);

updated :处于数据更新的后

updated() {
    console.log("1:",this.$refs.page)
    this.pageList = this.$refs.page;
}

延时方法不推荐使用,存在不确定性。

 

 

 

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值