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!
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
orundefined
) will not cause an error. The short-circuit return value of this expression isundefined
. When used with function calls, returnsundefined
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] // 冰墩墩
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.
I believe that all of you are not ordinary people. Since it can be used injs
, we will follow the idea to solve this problem
3. Solution
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']) //冰墩墩
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 optimizedlet 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] !== '') tempObj = tempObj?.[keys[i]]
}
return tempObj
}
console.log(variableJudge(obj, '.a.b.c.0')) //冰墩墩
Vue.prototype.$vj = variableJudge
Let’s take a look at how to use it in the template
// 省去了臃肿的代码为空判断 是不是赏心悦目了 <div>{{ $vj(ugc, '.itemList.item.pic.picList.1.picUrl') }}</div>
4. Summary
?. (Optional chain call operatorIf this article has helped you, you can share it with others) 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.
Now that you have seen this,
it is not easy to create, please leave a small like.
For more programming-related knowledge, please visit:
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!