1、babel配置
安装依赖
npm install @babel/plugin-proposal-optional-chaining
npm install @babel/plugin-proposal-nullish-coalescing-operator
根目录的 .babelrc 或者 babel.config.js 里配置两个插件:
const plugins = [
// 双问号
'@babel/plugin-proposal-nullish-coalescing-operator',
// 可选链
'@babel/plugin-proposal-optional-chaining'
]
module.exports = {
plugins
}
2、vue模板中使用
目前vue默认不支持template使用可选链式操作符,如果想要使用:
utils.js
/**
* @description: 解决vue template模板中无法使用可选链的问题
* @param {*}
*/
export default function useChain(obj, keyName) {
console.log(obj, keyName)
if (!obj) return null
let keys = (keyName + '').split('.')
let tempObj = obj
for (let i = 0; i < keys.length; i++) {
if (!tempObj) return
if (keys[i] !== '') tempObj = tempObj?.[keys[i]]
}
return tempObj
}
main.js
import { useOptionChain } from '@/utils/utils';
Vue.prototype.optionChain = useChain; //配置全局template使用可选链
template.vue
<template>
<div id="app">
//保留可选链的写法,更直观的展示,想要拿数组的元素直接取下标的数字即可,不需要 []
<h1 v-if="optionChain(arr,'0?.obj?.a?.b')">数组对象</h1>
</div>
</template>
<script>
export default {
name: "App",
components: {},
data() {
return {
arr: [
{
obj: {
a: {
b: "数组对象",
},
},
},
]
};
}
};
</script>