写在前面
总觉得工作的时候比上学的时间还要快,转眼间入职已经有小半年了,如果问我从0开始写前端是什么感觉,那就是……真的太细了……🤏满满的都是细节有木有!做前端项目就像是下雨走路,看起来是个小水洼,结果踩上去是个大水坑,而且到处都是……下面这些坑就是我踩过的或大或小的坑,一起来看看吧!
1. 路由的带参跳转
场景:
从一个页面跳转到另外一个页面的时候,下面一个页面需要用到上一个页面的参数去做一些查询操作,会带一个或者多个参数,我是这么实现的:
params传参
// 注意一定要用name,如果用path的话params会失效
// $router为路由操作对象,为只写对象
this.$router.push({
name:'gamedetail',
params:{
id:id,
channel:channel
}
})
// params接收参数
// $route为路由信息对象,为只读对象
this.id = this.$route.params.id;
this.code = this.$route.params.code
然而用params传参,在刷新后参数会丢失,同样的还有vuex,刷新后在store里存储的信息一样会消失😅这个之后再讲。。。params参数刷新后消失,是因为这个传参方式相当于post方法,携带的参数不会拼接到页面路径。
所以,还有一种query传参的方法,相当于get方法,携带的参数能在url上直接看到,即使刷新页面,参数也会一直保留。query既可以用path也可以用name。
query传参
//query传参,使用name跳转
this.$router.push({
name:'gamedetail',
query:{
id:id,
channel:channel
}
})
//query传参,使用path跳转
this.$router.push({
path:'gamedetail',
query:{
id:id,
channel:channel
}
})
//query接受参数
this.id = this.$route.query.id;
this.code = this.$route.query.code;
router-link
还可以使用router-link,就像是a标签一样,点击可以跳转:
<router-link :to="{name: 'gamedetail', params: { id:id,channel:channel }}">详情</router-link>
<router-link :to="{name/path: 'gamedetail', query: { id:id,channel:channel }}">详情</router-link>
此外要注意的是,传过去的参数只能为字符串,不能为对象,如果是要将一整个对象传过去,可以使用JSON.stringify(你的对象)转成字符串,然后在接收端使用JSON.parse()还原哦~😄
动态路由传参:
{
nameL: "gamedetail"
path: "/gamedetail/:id",
component: "GameDetail"
}
第一种方法:
<router-link to="/gamedetail/1">详情</router-link>
第二种方法:
this.$router.push('/gamedetail/${id}')
第三种方法:
this.$router.push({ name: "gamedetail", params: { id: '1' } });
2.对象的浅拷贝及深拷贝
场景:在页面上显示一条数据的详细信息的时候,往往会使用v-model创建双向绑定,然而如果还有编辑功能,如果表单信息和数据的详细信息绑定的是同一个对象……开始,我是这么做的:
赋值
let gameInfo = {name:"paopaolong", publisher:"oppo"}
let currentGameInfo = gameInfo
console.log(gameInfo)//{name:"paopaolong",publisher:"oppo"}
console.log(currentGameInfo)//{name:"paopaolong",publisher:"oppo"}
然而,直接赋值会让currentGameInfo和gameInfo一样指向的是栈中的地址,而不是堆中的数据,因此就会出现表单的数据变化,而页面上的详细信息同步变化的情况
浅拷贝
浅拷贝会在堆中创建内存,拷贝前后对象的基本数据类型互不影响,但拷贝前后的对象引用类型因共享同一块内存,会相互影响。
实现方式:Object.assign()
let gameInfo = {name:"paopaolong", arr:[1,[2,3]],4}
let currentGameInfo = Object.assign({},gameInfo)
currentGameInfo.name = "7788"
currentGameInfo.arr[1] = [5,6,7] //浅拷贝改变了对象的引用
console.log(gameInfo)// {name:"paopaolong", arr:[1,[5,6,7]],4}
console.log(currentGameInfo)// {name:"7788", arr:[1,[5,6,7]],4}
深拷贝
深拷贝是从堆中开辟了一个新区域存放对象,堆对象中的子对象进行递归拷贝,拷贝前后的两个对象互不影响
实现方式1:JSON.parse(JSON.stringify())
let arr = [1, 3, { username: ' kobe' }];
let arr1=JSON.parse(JSON.stringify(arr))
arr1[2].username = 'demo';
arr1[0]=18,
console.log(arr)//[1, 3, { username: ' kobe' }]
console.log(arr1)//[18, 3, { username: ' demo' }]
实现方法2:写成util方法
export const copy = (dest, src) => {
dest = dest || {};
for (var p in src) {
if (typeof src[p] === "object") {
copy(src[p], dest[p]);
} else {
dest[p] = src[p];
}
}
return dest;
}
未完待续……