温馨提示×

首页 > 教程 > 编程开发 > Vue.js基础教程 > Vue Router的基本使用

Vue Router的基本使用

Vue Router是Vue.js官方的路由管理器,它和Vue.js完美地结合在一起,可以实现SPA(Single Page Application)应用程序的开发。在本教程中,我们将讲解Vue Router的基本使用方法。

1. 安装Vue Router

首先,我们需要安装Vue Router。可以使用npm或者yarn进行安装:

npm install vue-router
# 或者
yarn add vue-router

2. 创建路由实例

在Vue应用程序中,我们需要先创建一个路由实例。在项目的入口文件(通常是main.js)中,我们需要引入Vue和Vue Router,并创建一个新的路由实例:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // 在这里配置路由
  ]
})

3. 配置路由

在路由实例中,我们需要配置路由。每个路由都是一个对象,包括路径和对应的组件。在例子中,我们创建两个路由:

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About }
  ]
})

4. 创建路由组件

在路由配置中,我们引用了两个组件HomeAbout,这两个组件需要事先定义。在Vue应用程序中,我们可以通过Vue组件来定义:

<template>
  <div>
    <h2>Home</h2>
    <p>Welcome to Home page!</p>
  </div>
</template>

<script>
export default {
  name: 'Home'
}
</script>
<template>
  <div>
    <h2>About</h2>
    <p>Welcome to About page!</p>
  </div>
</template>

<script>
export default {
  name: 'About'
}
</script>

5. 将路由实例挂载到Vue实例上

最后,我们需要将路由实例挂载到Vue实例上,这样路由才能生效。在Vue实例的配置中,我们加入路由:

new Vue({
  el: '#app',
  router,  // 将路由实例加入Vue实例中
  render: h => h(App)
})

6. 在模板中使用路由

现在,我们就可以在模板中使用路由了。可以通过<router-link>组件来创建路由链接,通过<router-view>组件来显示当前路由对应的组件。

<template>
  <div>
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>

    <router-view></router-view>
  </div>
</template>

7. 运行应用程序

现在,我们已经完成了Vue Router的基本配置,可以运行我们的应用程序了。在命令行中运行以下命令:

npm run serve

然后打开浏览器访问http://localhost:8080,就可以看到我们创建的SPA应用程序了。

以上就是Vue Router的基本使用方法。希望本教程对你有帮助。如果有任何问题,请随时留言。