vue简单路由(一)

在项目中,将vue的单页面应用程序改为了多页面应用程序,因此在某些场景下,需要频繁的切换两个页面,因此考虑使用路由,这样会减少服务器请求。

使用vue-cli(vue脚手架)快速搭建一个项目的模板(webpack-simple),运行起来后,将原来index.html页面挂载点中的内容删除

index.html 

<div id="app">
<!-- 使用 router-link 组件来导航,通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/home">
 	<button>home</button>
</router-link>
<router-link to="/game">
   	<button>game</button>
</router-link>
<!-- router-view 路由出口, 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>


router-link会被默认渲染成一个a标签,如下图

main.js,定义路由时,将每个路由映射到组件,路由其实也就是引入组件

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//引入两个组件
import home from "./home.vue"
import game from "./game.vue"

//定义路由,将每个路由映射到组件
const routes = [
   { path: "/home", component: home},
   { path: "/game", component: game},
]
//创建路由实例
const router = new VueRouter({routes})

new Vue({
   el: '#app',
   data: {
   },
   methods: {
   },
   router
})


home.vue

<template>
	<h3>首页</h3>
</template>

game.vue

<template>
	<h3>游戏</h3>
</template>

点击 home 或者 game 按钮时,就会显示相应的内容,如下图:

原文地址:https://www.cnblogs.com/dwj88/p/7877866.html