来源: 吾推网  发布时间: 2022-07-21   次浏览

vuecli3以后的脚手架好像可以直接用,测试用的vuecli4是可以的,否则需要安装相关依赖,并在plugins上配置
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-nullish-coalescing-operator',
'@babel/plugin-proposal-logical-assignment-operators'

1.可选链(?.)运算符,当访问属性的链式过程中如果遇到没有的属性则返回undefined,没使用的情况是会报错

    let test = {
      a: [{
        c: 1
      }]
    }

    let b = test?.a?.[0].c // 1
    let b = test?.b?.[0].c // undefined

2.空值合并运算符(??)

    let b
    let a = null
    let c = 'test'
    b = a ?? c
    console.log(b) // test

    let b
    let a = 0
    let c = 'test'
    b = a ?? c
    console.log(b) // 0

上面的例子,当a除了undefined、或者null之外的任何值,b都会等于a,否则就等于c

3.空值赋值运算符(??=)

    let a = 999
    let b = 888
    b ??= a
    console.log(b) // 888

    let a = 999
    let b = null
    b ??= a
    console.log(b) //  999

当??=左侧的值为null、undefined的时候,才会将右侧变量的值赋值给左侧变量.其他所有值都不会进行赋值,vuecli4脚手架默认不支持,得安装相关插件