gpt4 book ai didi

javascript - 为什么 VueJS 没有在 html 中显示我的嵌套路由?

转载 作者:行者123 更新时间:2023-12-02 22:42:16 25 4
gpt4 key购买 nike

我正在通过阅读文档来学习 VueJS 路由。我从页面中打开了一个示例,并将自己的嵌套路由添加为“/user/foo/posts/1、/user/foo/posts/2、/user/foo/posts/3”,并期望它们能够正确显示

我尝试仔细阅读起始示例以及路由文档( Nested Routes 上的页面)。没有任何线索让我知道出了什么问题。

代码如下:

HTML:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
<p>
<router-link to="/user/foo">/user/foo</router-link>
<router-link to="/user/foo/profile">/user/foo/profile</router-link>
<router-link to="/user/foo/posts">/user/foo/posts</router-link>
<!-- stuff I added myself below this line (comment is not present in original code) -->
<router-link to="/user/foo/posts/1">/user/foo/posts/1</router-link>
<router-link to="/user/foo/posts/2">/user/foo/posts/2</router-link>
<router-link to="/user/foo/posts/3">/user/foo/posts/3</router-link>
</p>
<router-view></router-view>
</div>

JS:

const User = {
template: `
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
`
}

const UserHome = { template: '<div>Home</div>' }
const UserProfile = { template: '<div>Profile</div>' }
const UserPosts = { template: '<div>Posts</div>' }

const PostOne = { template: '<p>Gonna clone Twitter</p>'}
const PostTwo = { template: '<h5>Not gonna clone IG until Im done Twitter</h5'}
const PostThree = { template: '<p>Gonna be a paid web developer</p>'}

const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
// UserHome will be rendered inside User's <router-view>
// when /user/:id is matched
{ path: '', component: UserHome },

// UserProfile will be rendered inside User's <router-view>
// when /user/:id/profile is matched
{ path: 'profile', component: UserProfile },

// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
{ path: 'posts', component: UserPosts,
children: [
// the posts within /posts
{ path: "1", component: PostOne },
{ path: "2", component: PostTwo },
{ path: "3", component: PostThree }
]
}
]
}
]
})

const app = new Vue({ router }).$mount('#app')

具体来说,我希望/1 说“要克隆 Twitter”,/2 说“在完成 Twitter 之前不会克隆 IG”(在 h5 标签中),/3 说“要成为付费网站”开发商”。

我希望看到这些文本加载在“用户 foo单击链接时发布“帖子”,但我没有。

编辑:请注意,我只尝试在 JSFiddle 环境中运行它。这是 fiddle 本身,我希望代码能够正常运行:https://jsfiddle.net/rolandmackintosh/use04pwf/9/

最佳答案

所以你面临的问题是你不仅嵌套路由,而且嵌套组件。当一个路由有它自己的组件和子路由时,需要有一个 <router-view>供 child 加载。此更改为 UserPosts会让它为你工作:

const UserPosts = { template: '<div>Posts<router-view></router-view></div>' }

关于javascript - 为什么 VueJS 没有在 html 中显示我的嵌套路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58546888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com