類型轉換
快速轉 Number
var a = '1'
console.log(typeof a)
console.log(typeof Number(a)) // 普通寫法
console.log(typeof +a) // 高端寫法
快速轉 Boolean
var a = 0
console.log(typeof a)
console.log(typeof Boolean(a)) // 普通寫法
console.log(typeof !!a) // 高端寫法
混寫
先轉爲 Number 再轉爲 Boolean
var a = '0'
console.log(!!a) // 直接轉將得到 true,不符合預期
console.log(!!+a) // 先轉爲 Number 再轉爲 Boolean,符合預期
js 和 css 兩用樣式
template 中需要動態定義樣式,通常做法:
<template>
<div :style="{ color: textColor }">Text</div>
</template>
<script>
export default {
data() {
return {
textColor: '#ff5000'
}
}
}
</script>
高端做法:
- 定義 scss 文件
$menuActiveText:#409EFF;
:export {
menuActiveText: $menuActiveText;
}
- 在 js 中引用:
- 使用 import 引用 scss 文件
- 定義 computed 將 styles 對象變成響應式對象
- 在 template 中使用 styles 對象
<template>
<div :style="{ color: styles.menuActiveText }">Text</div>
</template>
<script>
import styles from '@/styles/variables.scss'
export default {
computed: {
styles() {
return styles
}
}
}
</script>
連續解構
從數組第一個對象元素中提取某個屬性,比如:err 對象中包含一個 errors 數組,errors 數組每一個對象都包含一個 msg 屬性
err = {
errors: [
{
msg: 'this is a message'
}
]
}
快速的提取方法爲:
const [{ msg }] = err.errors
如果不用解構寫法爲:const msg = err.errors[0].msg