四时宝库

程序员的知识宝库

JS 传导运算符 Vue 对象链判断运算操作

VUE不能直接使用 ?. 问题

JS 代码

const obj = {
            a: {
                b: {
                    c:"1"
                }
            }
        }
//ES5 取c, 正确的做法是: 
const cValue = (obj && obj.a && obj.a.b && obj.a.b.c) || ''; 
// 需要判断4次,每一层是否有值

// ES6
const cValue = obj?.a?.b?.c  //1 

VUE2 需要配置使用

// 1. 安装依赖(Babel)
npm install @babel/plugin-proposal-optional-chaining --registry=http://registry.npm.taobao.org

// 2.添加至项目.babel.config.js文件中:
module.exports = {
  "plugins": [
    // Vue项目中支持可选链(链判断运算符)操作 ?.
    "@babel/plugin-proposal-optional-chaining",
 ]
}

// 3.实际中的示例
  data() {
    return {
      a: {
        b: { c: 1 },
      },
    };
  },
 mounted() {
    console.log(this.a?.b?.c); // 1
    console.log(this.a?.b?.d); // undefined
  },

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接