Vue命名路由

描述:

通过一个名称来标识一个路由显得更方便一些,特别是在链接一个路由,或者是执行一些跳转的时候。

使用:

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>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值