前言
单页应用(Single-page application, SPA)已经成为了现代网页开发的趋势,它能够大幅提升用户体验,而 Vue.js 已经成为了开发 SPA 的一种常用框架。在本文中,我们将通过一个实例来介绍如何使用 Vue 以及其路由插件 vue-router 来实现一个简单的单页应用。
准备工作
在开始之前,我们需要先安装好 Vue 和 vue-router。可以通过以下命令来安装:
npm install vue vue-router --save
示例应用
我们将实现一个简单的示例应用,该应用包含两个页面:主页和关于页。用户可以在这两个页面之间进行切换。下面是代码目录:
├── index.html
└── src
├── App.vue
├── main.js
└── router.js其中 index.html 是主入口页面,App.vue 是应用组件,main.js 是入口文件,router.js 是路由配置文件。
index.html
我们将在 index.html 中定义应用的主入口,以及引入应用的 JS 文件和 CSS 文件。
// www.javascriptcn.com code example <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue with vue-router</title> <link rel="stylesheet" href="https://unpkg.com/iview/dist/styles/iview.css"> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <script src="./dist/main.js"></script> </head> <body> <div id="app"></div> </body> </html>
App.vue
我们将在 App.vue 中定义应用的根组件。
// www.javascriptcn.com code example
<template>
<div>
<h1>Vue with vue-router</h1>
<ul>
<li><router-link to="/">主页</router-link></li>
<li><router-link to="/about">关于</router-link></li>
</ul>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>在上面的代码中,我们通过 <router-link> 组件展示了两个链接,每个链接对应一个页面,通过 <router-view> 组件来展示对应的组件。
main.js
我们将在 main.js 中定义应用的入口文件,包括创建 Vue 实例、配置路由等。
// www.javascriptcn.com code example
import Vue from 'vue'
import App from './App.vue'
import router from './router'
new Vue({
el: '#app',
router,
render: h => h(App)
})在上面的代码中,我们创建了一个带有路由配置的 Vue 实例,并将其挂载在 #app 对应的元素上。
router.js
我们将在 router.js 中定义应用的路由配置文件。
// www.javascriptcn.com code example
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
component: About
}
]
})在上面的代码中,我们配置了两个路由,/ 对应 Home 组件,/about 对应 About 组件。
Home.vue
// www.javascriptcn.com code example
<template>
<div>
<h2>首页</h2>
<p>Hello, Vue with vue-router!</p>
</div>
</template>
<script>
export default {
name: 'Home'
}
</script>About.vue
// www.javascriptcn.com code example
<template>
<div>
<h2>关于页</h2>
<p>Vue with vue-router 是一款前端框架。</p>
</div>
</template>
<script>
export default {
name: 'About'
}
</script>结语
本文主要介绍了如何使用 Vue 以及其路由插件 vue-router 来实现一个简单的单页应用,并给出了完整的示例代码。这个示例比较简单,但是已经能够说明如何在 Vue 中使用路由插件来实现单页应用。对于复杂的应用,类似的知识点还有很多,希望本文能对读者的学习和开发有所帮助。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/6780956bce7f48612541c8b6