1 安装插件cnpm install vue-router
2 配置main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Page1 from "./components/page1.vue";
import Page2 from "./components/page2.vue";
import News from "./components/news.vue";
const routes = [
{path:'/page1',component:Page1},
{path:'/page2',component:Page2},
{path:'/news/:aid',component:News},
{path:'*',redirect:'/page1'}
]
const router = new VueRouter({
mode:'history',//路由美化
routes
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
3 App.vue
<template>
<div id="app">
<br><hr>
<router-link to="/page1" >page1</router-link>
<router-link to="/page2" >page2</router-link>
<br><hr>
<router-view></router-view>
<br><hr>
<button @click="jstest()">js跳转</button>
</div>
</template>
<script>
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},methods:{
jstest(){
this.$router.push({path:'news/1'});
}
}
}
</script>
4 page2.vue
<template>
<div>
<h2>
{{msg}}
</h2>
<br><hr>
<ul>
<li v-for="(item,key) in list">
<router-link :to="'/news/'+key">{{item}}</router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data(){
return {
'msg':'I am msg from page2 component',
'list':['new1','new2','new3']
}
}
}
</script>
5 news.vue
<template>
<div>
<h2>
{{msg}}
</h2>
<br><hr>
</div>
</template>
<script>
export default {
data(){
return {
'msg':'this is content in news component',
}
},mounted(){
alert(this.$route.params['aid']);
}
}
</script>