在Vue3中使用keep-alive和route-view的时候,类似以下代码

<transition>
  <keep-alive>
    <router-view />
  </keep-alive>
</transition>

就会以下出现警告信息,目前发现两种原因导致

<router-view> can no longer be used directly inside <transition> or <keep-alive>

 

第一种是组件下使用的 

按照提示可以做下调整

模板组件

<router-view  v-slot="{ Component }">
  <transition>
    <keep-alive>
      <component :is="Component"></component>
    </keep-alive>
  </transition>
</router-view>

tsx组件,以下类似代码

interface IRouterViewSlot {    //自定义
	Component: VNode;
    route: RouteLocationNormalizedLoaded;
}

<RouterView v-slots={{
	default: ({ Component }: IRouterViewSlot) => {
		return (
			<>
				<Transition name="fade" mode="out-in">
					<KeepAlive>
						{createVNode(Component)}
					</KeepAlive>
				</Transition>
            </>
			)
		},
	}}
></RouterView>

第二种原因是路由配置了routerview组件(没有这样配置的可以忽略)
 

同样也是出现此警告信息

<router-view> can no longer be used directly inside <transition> or <keep-alive>

解决办法就是单独写一个RouterView组件(tsx 或者 模板组件都可以)
 以下使用的是tsx

import {createVNode, defineComponent, KeepAlive, SetupContext, Transition, VNode} from 'vue'
import { RouterView,RouteLocationNormalizedLoaded } from 'vue-router'

interface IRouterViewSlot {
	Component: VNode;
    route: RouteLocationNormalizedLoaded;
}
export default defineComponent({
	name:'BasicRouterView',
	props:{},
	setup(props, {slots}:SetupContext) {
		return () => (
			<>
				<RouterView
					v-slots={{
						default: ({ Component }: IRouterViewSlot) => {
							return (
								<Transition name="fade" mode="out-in">
                                    <div>
									    <KeepAlive>
										    {createVNode(Component)}
									    </KeepAlive>
                                    </div>
								</Transition>
							)
						},
					}}
				></RouterView>
			</>
		)
	},
	mounted() {
	}
})

最后在路由配置文件里把RouterView替换成上面的组件即可

Logo

前往低代码交流专区

更多推荐