这是我参与8月更文挑战的第1天,活动详情查看:8月更文挑战
1、vue-router的redirect属性使用
如果页面有判断vuex的值是否存在,存在则使用vuex的值,否则走默认值这样的写法。 这种vuex存值一般只在自己流程中使用,其他模块跳转过来就要重置一下vuex的默认值,但又不想在很多地方重置,所以可以用如下的方法来处理:
注:redirect的当前路由不会记入routerList
// router 配置
{
path: '/xxxx/xxx/initIndex',
redirect: () => {
sessionStorage.setItem('item_vuex', 'Y');
return '/xxxx/xxxx/index';
}
},
{
path: '/xxxx/xxxx/index',
component: index,
meta: {
title: 'title'
}
}
// 页面逻辑
const item_vuex = sessionStorage.getItem('item_vuex');
if (item_vuex === 'Y') {
// 执行一些重置方法
this.reset();
// 清除sessionStorage指定的值
sessionStorage.removeItem('item_vuex');
}
2、JS原生面向对象不能混用ES6语法
在用JS原生面向对象如果用到了async/await语法糖,保存是会报错
Cannot assign to read only property 'exports' of object
3、成功页返回处理
let index = window.routerList.indexOf(targetUrl);
let currIndex = window.routerList.indexOf(this.$route.fullPath);
if (index > -1) {
window.routerList.splice(index + 1, currIndex - index - 1);
}
if (!window.isApp) {
const fullPath = this.$route.fullPath;
const Url = document.URL;
history.pushState(null, null, Url);
window.addEventListener('popstate', () => {
if (this.$route.fullPath === fullPath) {
history.pushState(null, null, Url);
}
});
}
4、函数式组件
优化前的组件代码如下:
<template>
<div class="cell">
<div v-if="value" class="on"></div>
<section v-else class="off"></section>
</div>
</template>
<script>
export default {
props: ['value'],
}
</script>
优化后的组件代码如下:
<template functional>
<div class="cell">
<div v-if="props.value" class="on"></div>
<section v-else class="off"></section>
</div>
</template>
5、局部变量
如果computed定义的字段里有循环可以考虑使用局部变量
<script>
export default {
props: ['start'],
computed: {
base () {
return 42
},
result ({ base, start }) {
let result = start
for (let i = 0; i < 1000; i++) {
result += Math.sqrt(Math.cos(Math.sin(base))) + base * base + base + base * 2 + base * 3
}
return result
},
},
}
</script>
6、使用 Deferred 组件延时分批渲染组件
组件代码:
export default function (count = 10) {
return {
data () {
return {
displayPriority: 0
}
},
mounted () {
this.runDisplayPriority()
},
methods: {
runDisplayPriority () {
const step = () => {
requestAnimationFrame(() => {
this.displayPriority++
if (this.displayPriority < count) {
step()
}
})
}
step()
},
defer (priority) {
return this.displayPriority >= priority
}
}
}
}
使用:
<template>
<div class="deferred-on">
<template v-if="defer(2)">
<Heavy v-for="n in 8" :key="n"/>
</template>
<Heavy v-if="defer(3)" class="super-heavy" :n="9999999"/>
</div>
</template>
<script>
import Defer from '@/mixins/Defer'
export default {
mixins: [
Defer(),
],
}
</script>
7、Live Server 快速启动文件或文件夹服务
如果有sudo权限,可以直接全局安装
sudo npm install -g live-server
没有sudo权限,VSCode插件直接搜索Live Server安转即可。
8、采用hash模式跳转路由时,如果使用的动态路由参数,需要注意以下问题
path: 'user/login/:type'
那么其他路由就不能这样写 path: 'user/login/register'
这样写也是会认为是动态路由的参数
可以做一下操作path: 'user/login/common/:type' 多加一级来避免