uni-app vue2 在页面使用template嵌入其他页面的内容
时间: 2024-11-09 12:21:00 浏览: 65
在uni-app(基于Vue2的跨平台框架)中,如果你想要在一个页面中嵌入另一个页面的内容,你可以使用`<keep-alive>`组件配合动态路由来实现内容复用。步骤如下:
1. **设置动态路由**:首先,在需要嵌入页面的父组件的`pages.json`文件里,给目标页面添加一个动态路径。例如:
```json
{
"pages": [
{
"path": "parent-page",
"component": "parentPage.vue",
"children": [
{"path": ":childPage", "component": "childPage.vue"}
]
}
]
}
```
2. **动态加载组件**:在`parentPage.vue`中,使用`<router-view>`标签,并包裹在`<keep-alive>`内,这样当切换子页面时,之前的内容会被缓存起来:
```html
<template>
<view>
<keep-alive>
<router-view :key="$route.path"></router-view>
</keep-alive>
</view>
</template>
```
3. **跳转到嵌入页面**:在`parentPage.vue`中通过`this.$router.push`或者导航守卫`beforeRouteUpdate`来动态切换子页面:
```javascript
methods: {
loadChildPage(pageName) {
this.$router.push(`/parent-page/${pageName}`);
}
}
// 或者使用路由守卫
beforeRouteUpdate(to, from, next) {
if (to.name !== 'parent-page') return;
// 在这里加载你想嵌入的页面内容
let childContent = getEmbeddedContent('childPage.vue');
this.$refs.contentSlot.appendChild(childContent);
next();
}
```
4. **接收和显示嵌入内容**:在父页面的模板中,你可以选择一个slot(如`.vue`文件中的`<slot name="contentSlot">...</slot>`) 来放置子页面的内容。
阅读全文
相关推荐


















