Vue-Router 怎么配置路由

本文详细介绍了在Vue.js应用中配置路由的步骤,包括安装Vue Router、注册和使用路由器、配置路由项、引入组件、在main.js中调用配置、在App.vue中展示路由和进行路由切换。通过这些步骤,可以实现Vue应用的页面跳转和组件显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Vue中配置路由一般分为以下几个步骤,分别是:

1. 安装

npm install --save Vue-Router

2. 在src/router.index.js中引入 

import Vue from 'vue'
import Router from 'vue-router'

3. 使用/注册

Vue.use(Router)
//要告诉 vue 使用 vueRouter

4. 配置路由

export default new Router({
  routes: [
    {
      path: '/home',
      name: 'home',
      component: home
    },
    {
      path: '/about',
      name: 'about',
      component: about
    }
  ]
})

5.引入路由对应的组件地址

import home from '@/components/home'
import about from '@/components/about'

6. 在main.js中调用index.js的配置

import router from './router'

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

7. App.vue页面使用(展示)路由:把这个标签放到对应位置:

<router-view></router-view>

8. 路由切换(原来的<a href=”XXX.html”>等地方):把切换标签和链接改成:

<router-link to="/home">home</router-link>
<router-link to="/about">about</router-link>

源码如下:

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
 
Vue.config.productionTip = false
 
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

src/router/index.js'

import Vue from 'vue'
import Router from 'vue-router'
import home from '@/components/home'
import about from '@/components/about'
 
Vue.use(Router)
//要告诉 vue 使用 vueRouter
export default new Router({
  routes: [
    {
      path: '/home',
      name: 'home',
      component: home
    },
    {
      path: '/about',
      name: 'about',
      component: about
    }
  ]
})

App.vue 展示路由 和 路由切换

<template>
  <div id="app">
    <router-link to="/home">home</router-link>
    <router-link to="/about">about</router-link>
    <router-view></router-view>
  </div>
</template>
 
<script>
export default {
  name: 'App'
}
</script>
 
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值