- 创建一个新的脚手架
- 清除多余的文件
- 下载vue-router
- 在main.js中导入相关信息
-
安装
yarn add vue-router
-
导入路由
import VueRouter from 'vue-router'
-
注册
// 在vue中,使用使用vue的插件,都需要调用Vue.use()
Vue.use(VueRouter)
-
创建路由规则数组
const routes = [
{
path: "/find",
component: Find
},
{
path: "/my",
component: My
},
]
二级路由:
{
path: '/find',
name:'Find',
component: Find,
children: [
{
path: 'xiaowugui',
component:xiaowugui
},
{
path: 'xiaowoniu',
component:xiaowoniu
}
]
},
懒加载式创建路由规则:
不需要这样import Find from './views/Find.vue'导入
而是直接写在规则l
{
path: 'artlist',
name: 'artlist',
component: () => import('../views/artlist/index.vue')
},
-
创建路由对象 - 传入规则
const router = new VueRouter({
routes
})
-
关联到vue实例
new Vue({
router
})
-
components换成router-view
-
你在需要输出路由的地方使用.
<router-view></router-view>
总结: 下载路由模块, 编写对应规则注入到vue实例上, 使用router-view挂载点显示切换的路由
总结2: 一切都围绕着hash值变化为准
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
//这里是导入你所需要的文件
import Find from './views/Find.vue'
import My from './views/My.vue'
import Part from './views/Part.vue'
Vue.use(VueRouter)
//根据导入文件创建对应的内容
const routes = [{
path: '/find',
component:Find
},{
path: '/my',
component:My
},{
path: '/part',
component:Part
}]
const router = new VueRouter({
routes
})
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
或者单独创建一个router文件夹.在router文件夹中创建一个index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Find from '../views/Find.vue'
import My from '../views/My.vue'
import Part from '../views/Part.vue'
Vue.use(VueRouter)
const routes = [{
path: '/find',
component:Find
},{
path: '/my',
component:My
},{
path: '/part',
component:Part
}]
const router = new VueRouter({
routes
})
//导出然后在main.js中接收
export default router
//main.js中写入下面代码
import router from './router/index'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
传值方法:
声明式导航传值方法1
语法:
to='/访问的路径(要传给谁)?参数名字=传送的值
<router-link to='/path?参数名=值'>方法1</router-link>
接收:
<p>方法1:{{ $route.query.name }}</p>
方法2
语法:
to='/访问的路径(要传给谁)/值'
找到你的规则文件在对应的地方修改
path: '/part/:username',
component:Part
<router-link to='/part/方法2'>方法2</router-link>
接收:
<p>方法2:{{ $route.params.username }}</p>
推荐使用js传值..
fn(){
this.$router.push({
name:'My',
params:{
username:'JS传值'
},
query:{
name:'JS传值2'
}
})
}
//通过this.$router.push({
name:'' //找到对应的路由组件
params:{
username:'JS传值'
},//输出你需要传送的值.
)}
-----------------------------------
//在另一边接收
<p>JS传值方法1:{{$route.params.username}}</p>
<p>JS传值方法2:{{$route.query.name}}</p>
设置默认第一次打开默认访问的路径
在定义的规则中第一条设置
{
path: '/',
component:Find(你所选择默认第一次打开网页对应的地方)
},
当找不到对应的网址的时候设置一个没有页面的消息
在规则中最后一条设置.当所有路劲都无法匹配的时候默认显示你的Node文件内容.
{
path: '*',
component:Node
}
修改路由的模式
不设置就默认字段带有#.
如果设置了就没有.
mode:'history'
const router = new VueRouter({
routes,
mode:'history' //默认不写就是带有#号的路由路径
})