// 安装依赖 npm install @babel/plugin-proposal-optional-chaining -S // @babel/plugin-proposal-nullish-coalescing-operator -S // 在babel.config.js中 的 plugins中添加 "@babel/plugin-proposal-optional-chaining" module.exports = { plugins: [ '@babel/plugin-proposal-optional-chaining', //可选链 ?. '@babel/plugin-proposal-nullish-coalescing-operator' //空值合并 ?? ] }
const chaining = { install(vue) { const optionalChaining = (obj, ...rest) => { let tmp = obj; for (let key in rest) { let name = rest[key]; tmp = tmp?.[name]; } return tmp || ""; } // 添加实例方法 vue.prototype.$$= optionalChaining } } export default chaining