index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>learnvuerouter</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
app.vue
<template>
<div id="app">
<button @click="homeClick">首页</button>
<button @click="aboutClick">关于</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
methods:{
homeClick(){
this.$router.push('/home')
},
aboutClick(){
this.$router.push('/about')
},
}
}
</script>
<style>
</style>
index.js
import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from '../components/Home'
import About from '../components/About'
Vue.use(VueRouter)
const routes = [{
path: '/home',
component: Home
},
{
path: '',
component: About
},
]
//安装插件
const router = new VueRouter({
//配置之间的关系
routes
})
export default router
App.vue
<template>
<div id="app">
<button @click="homeClick">首页</button>
<button @click="aboutClick">关于</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
methods:{
homeClick(){
this.$router.push('/home')
},
aboutClick(){
this.$router.push('/about')
},
}
}
</script>
<style>
</style>
Home.vue
<template>
<div>
<h2>
我是首页
</h2>
<p>我是首页内容</p>
</div>
</template>
<script>
export default{
name:"Home"
}
</script>
<style scoped>
</style>
运行结果