vue3中语法糖使用ref获取子组件方法/属性

997 阅读1分钟

场景:vue3 setup语法糖场景中,如果一些组件是需要是在回调中渲染的,那么就可能出现获取不到子组件方法的情况。

解决办法:和vue2一样,使用 nextTick()函数

子组件

<script setup>
	import { Popup, Field, Button, Icon, Toast, Dialog, Notify } from "vant";
	import { reactive, onMounted, getCurrentInstance } from "vue";
	let eUser = JSON.parse(localStorage.getItem("eUser"));
	const openPopup = () => {	
	  popupInfo.showPopup = true;
	};
	defineExpose({	//暴露函数给父组件
	  openPopup,
	});
};
 </script>
 //其中子组件中需要获取 localStorage 中的用户对象。但是此用户对象是经过父组件的异步请求之后才存储的。所以此时就出现了需要在请求之后再渲染出现子组件的场景。

父组件

//调用子组件

<showChannelInfo ref="popupChild" @changeBlur="changeBlur" v-if="childFlag"></showChannelInfo>
<script setup>
const childFlag = ref(false); //组件是否显示的标识,默认为隐藏
const popupChild = ref(""); //获取组件实例
//发起请求
Axios.then(()=>{
	 localStorage.setItem("eUser",eUser); //保存用户信息
	 childFlag.value = true; //展示子组件
	  nextTick(() => {	//注意,此处如果不用nextTick,会调用不到子组件函数,抛出异常。
         popupChild.value.openPopup();
      });
})
</script>