一 创建测试项目
vue init webpack-simple vuedemo
二 进入demo目录
cd vuedemo
三 安装依赖
cnpm install
四 安装 vue-router
cnpm install vue-router --save
五 修改代码
├── src
│ ├── App.vue
│ ├── components
│ │ ├── Content.vue
│ │ ├── Home.vue
│ │ ├── News.vue
│ │ └── Pcontent.vue
│ ├── main.js
App.vue
<template>
<div id="app">
<router-link to="/home">home</router-link>
<router-link to="/news">news</router-link>
<hr>
<br>
<router-view></router-view>
</div>
</template>
<script>
import Home from './components/Home.vue';
import News from './components/News.vue';
export default {
name: "app",
data() {
return {
msg:'hello vue world!',
};
},
components:{
'v-home':Home,
'v-news':News
},
};
</script>
<style>
</style>
Content.vue
<template>
<div id="content">
i am content
</div>
</template>
<script>
export default {
data(){
return {
msg: "content"
}
},
mounted(){
console.log(this.$route.params)
}
}
</script>
Home.vue
<template>
<!-- all content need in root-->
<div>
{{msg}}Home
<br>
<ul>
<li v-for="(item,k) in list" :key="item.id">
<router-link :to="'/pcontent?id='+k">{{k}} -- {{item}} </router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data(){
return {
msg:'i am home component!',
list:['goods1', 'goods2','goods3']
}
}
}
</script>
<style>
</style>
News.vue
<template>
<!-- all content need in root-->
<div>
{{msg}}News
<br>
<ul>
<li v-for="(item,k) in list" :key="item.id">
<router-link :to="'/content/'+k">{{k}} -- {{item}} </router-link>
</li>
</ul>
</div>
</template>
<script>
export default {
data(){
return {
msg:'i am news component!',
list:['111','222','333']
}
}
}
</script>
<style>
</style>
Pcontent.vue
<template>
<div id="content">
goods content
</div>
</template>
<script>
export default {
data(){
return {
msg: "content"
}
},
mounted(){
console.log(this.$route.query);
}
}
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Home from './components/Home.vue'
import News from './components/News.vue'
import Content from './components/Content.vue'
import Pcontent from './components/Pcontent.vue'
const routes = [
{path:'/home', component:Home},
{path:'/news', component:News},
{path:'/content/:aid', component:Content},
{path:'/pcontent', component:Pcontent},
{path:'*', redirect:''}
]
const router = new VueRouter({
routes
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
六 运行
npm run dev
七 总结
1 "域名/参数1/参数2" 子目录方式传参
《1 配置动态路由
routes:{
{path:'user/:id', component:Content}
}
《2 在模板上,用js字符串追加的方式传参数
<router-link :to="'/content/'+key">{{k}} -- {{item}} </router-link>
《3 在对应页面获取动态路由参数
this.$route.params
2 "域名?参数1=xxx&参数2=xxx" 方式传参
《1 配置动态路由
routes:{
{path:'/pcontent', component:Pcontent},
}
《2 在模板上,用js字符串追加的方式传参数
<router-link :to="'/pcontent?id='+k">{{k}} -- {{item}} </router-link>
《3 在对应页面获取动态路由参数
this.$route.query
八 参考
https://router.vuejs.org/
https://router.vuejs.org/zh/api/#to