Vue页面刷新后子组件丢失父组件传递的路由数据求助
问题描述
我正从父组件向子组件传递路由信息,但使用Ctrl+F5强制刷新页面时,子组件控制台接收的currentRoute数据有时为空,如何确保子组件能稳定获取父组件传递的路由数据?
子组件代码如下:
<script> export default { props: ["currentRoute"], methods: { _checkRoutes() { console.log("Child Component:: ", this.currentRoute); } }, mounted() { this._checkRoutes(); } } </script>
解决方案
1. 子组件监听props变化
给子组件添加watch监听currentRoute的变化,确保父组件更新数据时子组件能及时响应,同时设置immediate: true保证初始化时也能触发:
<script> export default { props: ["currentRoute"], methods: { _checkRoutes() { console.log("Child Component:: ", this.currentRoute); } }, mounted() { this._checkRoutes(); }, watch: { currentRoute: { immediate: true, handler(newVal) { if (newVal) { this._checkRoutes(); } } } } } </script>
2. 父组件控制子组件渲染时机
在父组件模板中用v-if判断,只有当currentRoute存在时才渲染子组件,避免子组件挂载时拿到空值:
<child-component v-if="currentRoute" :currentRoute="currentRoute"></child-component>
3. 子组件直接获取路由(推荐)
跳过父子组件传递,子组件直接通过Vue Router实例获取当前路由,彻底避免传递时机问题:
Vue 2选项式API
<script> export default { methods: { _checkRoutes() { const currentRoute = this.$route; console.log("Child Component:: ", currentRoute); } }, mounted() { this._checkRoutes(); // 监听路由变化 this.$watch('$route', () => { this._checkRoutes(); }); } } </script>
Vue 3组合式API
<script setup> import { useRoute, watch } from 'vue-router'; const route = useRoute(); const _checkRoutes = () => { console.log("Child Component:: ", route); }; _checkRoutes(); watch(route, _checkRoutes); </script>
4. 父组件等待路由就绪后赋值
如果父组件中路由数据初始化有延迟,可在beforeMount或$nextTick中赋值,确保路由数据就绪后再传给子组件:
<script> export default { data() { return { currentRoute: null }; }, beforeMount() { this.currentRoute = this.$route; } } </script>
内容的提问来源于stack exchange,提问作者harundogan
相关产品推荐
相关产品推荐

