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