(補充:是為了在 Vue 2中使用。Vue3原生支持)
js 新語法,可選鏈操作符(Optional chaining)“?.”,空值合並運算符(Nullish coalescing)“??”。它們在 vue 項目的模板里,默認是不可用的。需要引用 babel 開發依賴庫 vue-template-babel-compiler。
可選鏈操作符,如 a?.b?.c,如果 a 或 b 是 null 或者 undefined,則不會報錯,而是返回 undefined。這在 vue 模板里用起來方便。
空值合並運算符,如 a = b ?? c,當 b 為 null 或者 undefined 時,將 c 的值賦給 a。在 Java 模板 Freemarker 里有相似語法。
在 vue 項目里啟用這語法,參考庫官方文檔 https://www.npmjs.com/package/vue-template-babel-compiler 與 https://vuejsexamples.com/enable-optional-chaining-nullish-coalescing-and-many-new-es-syntax-for-vue-js-sfc-based-on-babel/
yarn add -D vue-template-babel-compiler --registry https://registry.npmmirror.com
(用 yarn 添加開發依賴,使用國內 npm 鏡像)
並且修改 vue.config.js 添加內容
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
options.compiler = require('vue-template-babel-compiler')
return options
})
}
}
如果原本有相關內容,則需要修改,合並進去。
可選鏈操作符,參考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining
空值合並運算符,參考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
另外,邏輯空賦值運算符,參考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
a ??= b,a 為 nullish 的值時才將 b 賦值給 a