描述:
通过一个名称来标识一个路由显得更方便一些,特别是在链接一个路由,或者是执行一些跳转的时候。
使用:
news.js(这个文件是从 index.js 文件中抽取拆分出来的,最终要被引入到 insex.js 文件中):
import News from '@/views/News'
import Detail from '@/views/Detail'
const routes = [
{
path: '/news',
component: News,
},
{
// 通过动态路由参数来完成页面数据的传递,这里是显示在地址栏上的,可以轻易变更
path: '/news/:id',
// 给当前规则起一个名称,用于路由跳转所用,这个名字是给程序看的
name: 'xw',
component: Detail,
},
]
export default routes
index.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import news from './routes/news'
// 以插件的方式添加
Vue.use(VueRouter)
// 实例化路由对象及配置路由表
const routes = [...news]
const router = new VueRouter({
// 路由模式
mode: 'history',
// 路由规则表
routes
})
export default router
new.json(虚拟新闻 mooc 数据):
[
{ "id": 1000, "title": "新闻1" },
{ "id": 2000, "title": "新闻2" },
{ "id": 3000, "title": "新闻3" }
]
new.vue(新闻页):
<template>
<div>
<ul>
<template v-if="news == null">
<li>加载中...</li>
</template>
<template v-else>
<li @click="godetail(item.id)" v-for="item in news" :key="item.id">{{ item.title }}</li>
</template>
</ul>
</div>
</template>
<script>
import { get } from '@/utils/http'
export default {
data() {
return {
news: null
}
},
async created() {
let ret = await get('/mock/news.json')
this.news = ret
},
methods: {
godetail(id) {
// 命名路由跳转
this.$router.push({
name: 'xw',
params: { id }
})
}
}
}
</script>
<style lang="scss" scoped></style>
detail.vue(新闻详情页):
<template>
<div>
<h3>props: {{ $route.params }} </h3>
</div>
</template>
<script>
export default {
};
</script>
<style lang="scss" scoped></style>