VUE es6技巧寫法(持續更新中~~~)

一些稍微優雅的技巧寫法,並非非的是es6,標題黨了哈

爲class綁定多個值

  • 普通寫法
:class="{a: true, b: true}"
  • 其餘
:class="['btn', 'btn2', {a: true, b: false}]"

一個值判斷a或者判斷b

  • 普通寫法
if(flg === a || flg === b)
  • 其餘
['a','b'].indexOf(flg) > -1
// 能夠使用Array.prototype.includes() 返回 Boolean
if(['a', 'b'].includes(flg)) {}

引用一個組件

  • 普通寫法
import a from './a.vue'
componets: {
    a
}
  • node寫法
components: {
    a: require('./a.vue')
}

V-FOR渲染

  • 通常
<li v-for="(item,index) in data" :key="index">
    {{item.uuid}} //輸出uuid字段
</li>
  • 解構賦值
<li v-for="{uuid} in data" :key="uuid">
    {{uuid}} //直接解構賦值輸出
</li>

CSS私有化

  • 通常
設置比較長的class類名區分,或者使用BEN等命名方法
  • css module
<style module>
    .h3 {}
</style>

style樣式會存在$style計算屬性中javascript

//調用方式
<h3 :class="$style.h3"></h3>
//$style是計算屬性,因此也能夠這樣 bool爲Bool表達式
<h3 :class="{$style.h3: bool}"></h3>
缺點: 生成一個獨一無二的class類名,只能使用類名class控制樣式
  • scoped
<style scoped>
</style>
生成Hash屬性標識.且 根元素父組件的scoped影響

解決辦法

使用 >>>深度選擇器
//尋找div下的樣式,包括子組件樣式
div >>> .h3 { }

對象操做

對象儘可能靜態化,一旦定義,就不得隨意添加新的屬性。若是添加屬性不可避免,要使用Object.assign方法。
// bad
const a = {};
a.x = 3;

// if reshape unavoidable
const a = {};
Object.assign(a, { x: 3 });

// good
const a = { x: null };
a.x = 3;
若是對象的屬性名是動態的,能夠在創造對象的時候,使用屬性表達式定義。
// bad
const obj = {
  id: 5,
  name: 'San Francisco',
};
obj[getKey('enabled')] = true;

// good
const obj = {
  id: 5,
  name: 'San Francisco',
  [getKey('enabled')]: true,  //屬性表達式 6
};

數組、對象參數使用擴展運算符(spread)

鏈接多個數組

  • 通常
let arr1 = [1,2,3]
let arr2 = [4,6,7]
arr2 =  arr2.concat(arr1)
  • spread 運算符
let arr1 = [1,2,3]
let arr2 = [...arr1,4,6,7]

鏈接多個json對象

  • 通常
var a = { key1: 1, key2: 2 }
var b = Object.assign({}, a, { key3: 3 })
// 最後結果
{key1: 1, key2: 2,key3: 3 }
  • spread 運算符
var a = { key1: 1, key2: 2 }
var b = {...a, key3: 3}

es6剩餘參數(rest paramete)

使用reset paramete是純粹的 Array實例
  • 通常
function a() {
    console.log(arguments)
}
a(1,2,3)
  • es6
function a(...args) {
    console.log(args)
}
a(1,2,3)

判斷數組是否包含指定值

IE 任何系列都不支持
  • 通常

須要本身寫工具函數css

  • es6
var arr = [1,2,3]
console.log(arr.includes(1)); // true
console.log(arr.includes(4)); // false

順序遍歷對象key值

IE 任何系列都不支持
  • es6
var obj = { key1: 1, key2: 2, key3: 3 }
Object.keys(obj); // ["key1", "key2", "key3"]

順序遍歷對象value值

IE 任何系列都不支持
  • es6
var obj = { key1: 1, key2: 2, key3: 3 }
Object.values(obj); // [1,2,3]

一行書寫多步操做

適用於只有兩三行簡單操做vue

var x = 1;
   var y = 1
   var z = x + y;
  • 使用逗號操做符
var z = (x=1, y = 1, x+ y)
當你想要在指望一個表達式的位置包含多個表達式時,能夠使用逗號操做符
相關文章
相關標籤/搜索