vue 使用可选链操作符

1,260 阅读1分钟

// 安装依赖

npm install @babel/plugin-proposal-optional-chaining -S 
@babel/plugin-proposal-nullish-coalescing-operator -S

在babel.config.js中 的 plugins中添加 "@babel/plugin-proposal-optional-chaining" 如果是在 vue.config.js中不要放

module.exports = {
            plugins: [
                     '@babel/plugin-proposal-optional-chaining', 
                     //可选链 ?.
                     '@babel/plugin-proposal-nullish-coalescing-operator' 
                     //空值合并 ?? 
                 ]
}

针对template模板中使用可选链操作符的办法:

  • utils.js
/*
    解决Vue Template模板中㞏使用可选链的问题
    @param obj
    @param rest
    @return {*}
*/
export const optionalChaining = (obj, ...rest) => {
    let tmp = obj;
    for(let key in rest) {
        let name = rest[key];
        tmp = tmp?.[name];
    }
    return tmp || '';
}

main.js

// 使template中可以使用可选链, 使用方法查看utils.js
import { optionalChaining } from "./plugins/utils.js"
Vue.prototype.$$ = optionalChaining

template 中使用


    <template>
        // 即使没有值也不会报错
        <div>{{$$(user, 'a', 'b')}}</div>
    </template>
    <script>
        export default{
            data() {
                return {
                    user: {
                        a: {
                            b:'ss'
                        }
                    }
                }
            }
        }
    </script>