1 get请求和post请求的区别
- get请求一般是去获取数据,post一般用于提交数据
- get请求参数放在url中,因此参数长度受限,post请求参数长度无限制且放在body中,要更安全
- get请求刷新浏览器或回退时没有影响,post请求回退时会重新提交数据
- get请求可被缓存,post请求不会被缓存
- get请求保存在浏览器历史记录中,post请求不会保存在历史记录中
- get请求只能进行url编码(application/x-www-form-urlencoded),post请求可以进行多种方式编码(application/x-www-form-urlencoded或multi/form-data)
- get请求产生一个TCP数据包,POST请求产生两个TCP数据包
- 对于get请求,浏览器会把http header和data一起发送出去,服务器响应200状态码;post请求会先发送header,服务器响应100 continue,浏览器再发送打他,服务器再响应200
2 动态路由匹配怎么实现
例如:有一个用户组件对所有用户进行渲染,但用户ID不同,可以在路径中使用一个动态字段来实现
const routes=[
{
path:'/user/:id',
component:()=>import('./User/user')
}
]
可以使用this.$route.param.id
获取到id参数
路由参数变化?
当用户切换时,即路由参数发生变化,使用复用方法会更加高效。要对同一个组件中参数变化做出响应,可以使用watch$route
对象上的任意属性,这里指的是$route.params
const User={
template:'...',
created(){
this.$watch(
()=>this.$route.params,(toParams,preParams)=>{
//对路由变化做出响应
})
}
}
也可以使用beforeRouteUpdate
导航守卫
3 使用vue-router
首先配置路径别名,在vue.config.js中配置
module.exports={
configureWebpack:{
resolve:{
alias:{
'assets':'@/assets',
'components':'@/components',
'router':'@/router',
}
}
}
}
之后为路由使用进行单独配置
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes=[{
path:'',
redirect:'/home'
},{
path:'/home'.
component:()=>import('components/Home.vue')
//嵌套路由
children:[{
path:'user'.
component:()=>import('components/Home.vue')
}]
}]
const router=new VueRouter({
routes,
mode:'history'
})
export default router
//最后将导出的router在main.js中引入使用即可生效
4 路由导航
(1)声明式:<router-link to='...'>
(2)编程式:router.push(...)
router.push的参数可以是路径字符串,也可以是描述地址的对象,他会返回一个promise对象
router.push('/user')
router.push({path:'/user'})
router.push({name:'user',params:{username:'xie'}})
router.push({path:'/user',query:{username:'zi'}}) // /user?username=zi
//如果提供了path,那么params会被忽略
const name='xie'
router.push(`/user/${name}`)
router.push({path:`/user/${name}`})
router.push({name:'user',params:{username}})
替换当前位置:router.place()
使用replace不会向history添加新记录
前进、后退
router.forward()
router.back()
router.go()
5 动态路由
动态路由主要由两个函数实现:router.addRoute()
和router.removeRoute()
查看现有路由:
router.hasRoute()
:检查路由是否存在router.getRoutes()
:获取一个包含所有路由记录的数组