1. 在router->index.js中,配置一个懒路由,定义页面加载哪个组件
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
]
// 配置一个懒路由,不然会加载页面下所有组件
const router = new VueRouter({
routes:[
{
path:'/home',
component:() => import('../views/Home.vue'),
}
]
})
export default router
2. 在App.vue中,通过router-view组件,引入这个router
this is app
注意,代码补全功能可以下载插件Auto Close Tag
1. App.vue通过router-link跳转
this is app
home
2. App.vue通过编程式导航
App.vue中,不是通过router-link,而是通过button绑定this.$router函数
this is app
this is app
index.js::在path后使用冒号标记url参数
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
]
// 配置一个懒路由,不然会加载页面下所有组件
// 动态路由,在home路径后面加个id,路径必须有id值,才能正确跳转,如:http://localhost:3333/#/home/1
const router = new VueRouter({
routes:[
{
path:'/home/:id',
component:() => import('../views/Home.vue'),
}
]
})
export default router
Home.vue : 在页面中,可以通过params获得参数内容
this is home
{{ $route.params.id }}
App.vue中,toHome()跳转时指定name和params参数,注意name要和params搭配!!!!params是路径参数,内容是放在路径/后面的。之前的跳转,path和query搭配,query是变量,内容是放在路径?后面的
this is app
在router中的index.js中,编辑路由,增加 name。
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
]
const router = new VueRouter({
routes:[
{
path:'/home/:id',
// 动态路由传参,根据name指定,需要多配置一个name
name:'home',
component:() => import('../views/Home.vue')
}
]
})
export default router
index.js 增加children
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
]
const router = new VueRouter({
routes:[
{
path:'/home/:id',
// 动态路由传参,根据name指定,需要多配置一个name
name:'home',
component:() => import('../views/Home.vue'),
Children:[{
path:'/child',
component:() => import('../views/Child.vue')
}]
}
]
})
export default router
home.vue,增加router-view
this is home
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
//导航守卫,每次切换路由时触发
router.beforeEach((to, from, next)=>{
console.log(to.path)
next()
})
// Vue.use(ElementUI);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')