我的index.js /
import Vue from 'vue';
import App from './App.vue';
import Users from './components/Users.vue';
import Home from './components/Home.vue';
import About from './components/About.vue';
import Contacts from './components/Contacts.vue';
import CategoryItemList from './components/CategoryItemList.vue';
import './static/css/main.css';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{path: '/users/:teamId', name: 'users', component: Users},
{path: '/', name: 'home', component: Home, children: [
{path: 'cat/:id', name: 'category-item-list', component:
CategoryItemList }]}];
const router = new VueRouter({mode: 'hash', routes});
export default new Vue({ el: '#root', router, render: h => h(App) });
我的组件包含类别列表和路由器链接/
<template lang="pug">
div
nav
<li v-for="category in categories" v-bind:category="category">
<router-link :to="{name: 'category-item-list', params: {id: category.id}
}">{{category.title}}</router-link>
</li>
</template>
<script>
export default {
name: "category-navigation",
data: function () {
return {
categories: [
{'title': 'first', 'id': 1},
{'title': 'second', 'id': 2},
{'title': 'third', 'id': 3}
]
}
}
}
</script>
我的类别//
的组件<template>
<div class="category" v-if="category">
<h1>{{category.title}}</h1>
<p>{{category.id}}</p>
<span>{{this.$route.params.id}}</span>
</div>
</template>
<script>
export default {
name: "category-item-list",
data: function () {
return {
categories: [
{'title': 'first', 'id': 1},
{'title': 'second', 'id': 2},
{'title': 'third', 'id': 3}
],
category: null
}
},
created: function () {
let catId = this.$route.params.id - 1;
console.log(catId);
console.log(this.$route.params.id);
this.category = this.categories[catId]
}
}
</script>
路线工作正常,我得到{{this。$ route.params.id}} 每次意义不同,但不改变类别。那些。变量catId一旦得到值并且没有改变。我做错了什么?
答案 0 :(得分:1)
问题与你的路线有关,特别是孩子:
const routes = [
{
path: '/users/:teamId',
name: 'users',
component: Users
},
{
path: '/',
name: 'home',
component: Home,
children: [
{
path: 'cat/:id',
name: 'category-item-list',
component: CategoryItemList
}]
}
];
将cat/:id
嵌套在/
路由下是不正确的,以及更大的问题是您没有为嵌套组件提供<router-view></router-view>
出口。来自文档:
a rendered component can also contain its own, nested <router-view>.
....
To render components into this nested outlet, we need to use the children option in VueRouter constructor config
仔细查看工作示例(如果还没有),这将更好地帮助您理解:
https://jsfiddle.net/yyx990803/L7hscd8h/
请参阅:https://router.vuejs.org/en/essentials/nested-routes.html
请注意,当页面与特定资源相关时,示例会嵌套路由,即顶级/cat/:id
,然后,/edit
作为子级,因此/cat/:id/edit
会结果。
答案 1 :(得分:0)
回答这个任务: 使用hook更新刷新变量catId:
created: function () {
let catId = this.$route.params.id - 1;
this.category = this.categories[catId]
},
updated: function () {
let catId = this.$route.params.id - 1;
this.category = this.categories[catId]
}enter code here