【vue学习】vue 实现路由

本文详细介绍了如何在Vue项目中实现路由功能,包括安装router、设计路由界面、创建静态路由表、引入并使用路由模块、测试路由以及获取路由参数的步骤。
摘要由CSDN通过智能技术生成

vue 实现路由

1. 安装router

npm install vue-router -s
npm install

2. 设计路由界面

src下新建views文件夹,新建Home.vue、Products.vue

<template>
  <div>home </div>
</template>

<script>
export default {

}
</script>

<style>

</style>

3. 创建静态路由表

src下新建routes.js

import Home from './views/Home'
import Products from './views/Products'

export const routes = [
    { path: '/home', component: Home },
    { path: '/products/:id', component: Products }
]

4. 引入路由模块并使用

在main.js引入

import Vue from 'vue'
import App from './App.vue'


import VueRouter from 'vue-router' //1. 引入路由模块
import {routes} from './routes' //2.引入静态路由表


Vue.use(VueRouter); //3.使用路由模块
//4.创建一个VueRouter模块的实例
const router = new VueRouter({
routes:routes
});

new Vue({
  el: '#app',
  router, //5.把router实例放入到vue实例中
  render: h => h(App)
})

5. 测试路由

<span>
    <router-link to="/home">home</router-link>
</span>  
<span>
    <router-link to="/products">product</router-link>
</span>

6. 获取路由参数

routes.js设置

export const routes = [
    { path: '/home', component: Home },
    { path: '/products/:id', component: Products }
]

组件内获取

<script>
export default {
  name: "Products.vue",
  data() {
    return {
      id: this.$route.params.id,
    }
  },
};
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值