做网站必须会编程吗,网页设计教材,重庆在线课程,网站建设旗帜条幅1. 路由的模式和区别 路由的模式#xff1a;history#xff0c;hash 区别#xff1a; 1. 表象不同 history路由#xff1a;以/为结尾#xff0c;localhost:8080——localhost:8080/about hash路由#xff1a;会多个##xff0c;localhost:8080/#/——localhost:…1. 路由的模式和区别 路由的模式historyhash 区别 1. 表象不同 history路由以/为结尾localhost:8080——localhost:8080/about hash路由会多个#localhost:8080/#/——localhost:8080/#/about 2. 关于找不到当前页面发送请求的问题 history会给后端发送一次请求所以history模式的时候一般会再配一个404页面 hash不会去发送请求 3. 关于项目打包前端自测问题 history模式下打包后默认情况下看不到内容需要额外去配置一些东西 hash模式下打包后可以看到内容 2. 子路由和动态路由 子路由是指在一个路由内定义的嵌套路由 动态路由是指在路由定义中使用动态段来匹配不同的参数。 const router new Router({mode: history,routes: [{path: /,name: home,component: Home},{path: /user/:id, /* /user/:id是一个动态路由其中:id是动态的参数 */name: user,component: User, /*父组件*/children: [{// 子路由path: profile,component: () import(./components/UserProfile.vue)},{// 子路由path: posts,component: () import(./components/UserPosts.vue)}]}]
})
/*在vue实例中使用router*/
// main.js
import Vue from vue
import App from ./App.vue
import router from ./router
new Vue({el: #app,router,render: h h(App)
})/* User.vue组件父组件 */
/* 当访问/user/123/profile或/user/123/posts时:id参数会被设置为123
子组件UserProfile.vue或UserPosts.vue会被渲染在User.vue的router-view/router-view中。*/
templatediv classuserh1User {{ $route.params.id }}/h1router-view/router-view /* 使用router-view/router-view来渲染子路由内容 *//div
/template
3. 路由传值 路由传值可以通过两种方式实现 1. 使用路由参数Params 2. 使用查询字符串Query 如果你需要在路由之间传递持续的、重要的信息使用路由参数可能更合适。 如果只是传递一些非必需的、临时的信息使用查询字符串可能会更好。 /* 使用路由参数 */
1. 路由配置
{path: /user/:id,name: user,component: User
}
2. 导航到路由并传递参数
this.$router.push({ name: user, params: { id: 123 }})
3. 接收参数在 User 组件内
created() {console.log(this.$route.params.id); // 输出123
}/* 使用查询字符串 */
1. 路由配置
{path: /user,name: user,component: User
}
2. 导航到路由并传递查询字符串
this.$router.push({ path: user, query: { name: John }})
3. 接收查询字符串在 User 组件内
created() {console.log(this.$route.query.name); // 输出John
}
4. 导航故障 当前页跳当前页时会出现的问题 /*解决方法*/
import VueRouter from vue-router
const routerPush VueRouter.prototype.push
VueRouter.prototype.push function (location) {return routerPush.call(this,location).catch(error error)
}
5. $router和$route区别 $router是一个大类不仅包含当前路由还包含整个路由的属性和方法 $route包含当前路由对象 6. 导航守卫
例如一个商城项目会有一个个人中心页假如个人中心页面有个我的订单模块如果已经登录的话那么点击我的订单就可以进入到我的订单页面如果没有登录的话点击我的订单就会跳转到登录页引导用户去登录。
const routes [{path: /,name: home,component: HomeView,},{path: /about,name: about,beforeEnter: function(to,from,next){if(true){next(); /*next()表示通行*/}else{next(/login);}}component: () import (../views/AboutView)}
] 1. 全局守卫 beforeEach路由进入之前 afterEach路由进入之后 2. 路由独享守卫 beforeEnter路由进入之前 3. 组件内守卫 beforeRouteEnter 路由进入之前 beforeRouteUpdate 路由更新之前 beforeRouteLeave 路由离开之前