Bootstrap

【vue学习】vue 实现路由

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>
;