Home > Web Front-end > Vue.js > This article will give you a detailed explanation of the optional chain call operator '?.' in Vue2.

This article will give you a detailed explanation of the optional chain call operator '?.' in Vue2.

青灯夜游
Release: 2022-02-14 20:34:08
forward
6710 people have browsed it

This article will take you through the optional chain call operator "?." in Vue2, and talk about how to use ?. in the template to solve the error. I hope it will be helpful to everyone!

This article will give you a detailed explanation of the optional chain call operator '?.' in Vue2.

First, let’s talk about what is?.(Optional chain call operator)

Optional chaining operator ( ?. ) allows reading the value of a property located deep in the connection object chain , without having to explicitly verify that each reference in the chain is valid. The function of the ?. operator is similar to the . chain operator, except that when the reference is empty (nullish) (null or undefined) will not cause an error. The short-circuit return value of this expression is undefined. When used with function calls, returns undefined if the given function does not exist. [Related recommendations: vue.js video tutorial]

Link: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/ Reference/Operators/Optional_chaining

To put it simply, we usually use the "." operator to get an upgraded version of a certain value of the object. When the previous value does not exist prevents undefined. things from reporting errors.
Without further ado, let’s get straight to the code.

let obj = { a: { b: { c: ['冰墩墩', '冬奥会'] } } }

// 当我们想获取“冰墩墩”的时候
// 如果直接obj.a.b.c[0]的话a、b、c任意一项不存在的话都会报错

// 正确的做法是
obj && obj.a && obj.a.b && obj.a.b.c && obj.a.b.c[0] // 冰墩墩

// 而采用?.操作符的话 
obj?.a?.b?.c?.[0] // 冰墩墩
Copy after login

When we encounter deeply nested data structures in our work, we use && to check whether the attributes exist. The code becomes very bloated. The readability and maintenance are mind-numbing. But using ?. is much simpler and the readability is greatly improved

2. Problems using ?. in Vue2 template

When we learn a new skill and want to show off in the world of code with great interest, we find that it can be used normally in Vue2 environment?., but in An error was reported in template.

This article will give you a detailed explanation of the optional chain call operator ?. in Vue2.

The ?. operator cannot be recognized normally in Vue2 template. It may be because the ?. optional chain syntax is relatively new and is not in the template. To deal with this aspect

I believe that all of you are not ordinary people. Since it can be used in
js

, we will follow the idea to solve this problem

3. Solution

    The _get method in the third-party library lodash
  • Upgrade By vue3, currently vue3 has become the default version. The ecology is approaching maturity and the template supports the optional chain operator
  • used in computed properties?.
  • Intercept changes to the template source code, the code is too intrusive
  • Write a hook and hang it on global/mixins to call it at any time
  • Think After a while, only the last solution is the most reliable. Let’s just do it. Let’s write our own?. Function
let obj = { a: { b: { c: ['冰墩墩', '冬奥会'] } } }

function variableJudge(obj, keyName, tag = '?.') {
  if (!obj) return undefined
  let keys = keyName.split(tag)
  return keys.reduce((objNew, keyItem) => {
    if (keyItem === '') return objNew
    if (keyItem.indexOf('.') !== -1) return variableJudge1(objNew, keyItem, '.')
    return objNew?.[keyItem]
  }, obj)
}
//------------------------------ Proxy 版本 --------------------------------------
function variableJudgeProxy(obj, tag = '?.') {
  if (!obj) return undefined
  return new Proxy(obj, {
    get: (obj, key) => {
      const keys = key.split(tag)
      return keys.reduce((objNew, keyItem) => {
        if (keyItem === '') return objNew
        if (keyItem.indexOf('.') !== -1) return variableJudgeProxy(objNew, '.')[keyItem]
        return objNew?.[keyItem]
      }, obj)
    }
  })
}
  console.log(variableJudge(obj, '?.a?.b?.c?.0')) //冰墩墩
  console.log(variableJudgeProxy(obj)['?.a?.b?.c?.0']) //冰墩墩
Copy after login

wait wait wait Since we want to write our own ?. function, why should we define that the passed in keyName contains ?.?

Why not let keyName directly be the . syntax and also have the function of ?. This is not only in line with our development habits, but also meets our expectations, wouldn't it be beautiful?And it stands to reason that if the previous value is undefined, we It should be reutrn directly, but it cannot be interrupted in advance using the reduce method.

So another version of the code was optimized

let obj = { a: { b: { c: ['冰墩墩', '冬奥会'] } } }

const variableJudge = (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] !== &#39;&#39;) tempObj = tempObj?.[keys[i]]
  }
  return tempObj
}
console.log(variableJudge(obj, &#39;.a.b.c.0&#39;)) //冰墩墩
Copy after login
Then we can hook it up to the Vue prototype and use it at any time

Vue.prototype.$vj = variableJudge
Copy after login

Let’s take a look at how to use it in the template

// 省去了臃肿的代码为空判断 是不是赏心悦目了
<div>{{ $vj(ugc, &#39;.itemList.item.pic.picList.1.picUrl&#39;) }}</div>
Copy after login

4. Summary

?. (
Optional chain call operator

) In fact, there are There are many wonderful functions waiting for everyone to discover. This article is just for?. Using error reporting issues in templates in Vue2 to expand

If there are any points in the article/code that can be optimized, everyone is welcome to suggest them.
If this article has helped you, you can share it with others

Now that you have seen this,
it is not easy to create, please leave a small like.

For more programming-related knowledge, please visit:

Programming Video

! !

The above is the detailed content of This article will give you a detailed explanation of the optional chain call operator '?.' in Vue2.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template