Learn about the new optional chaining operator (?.) in JavaScript and its application in Vue.js
Learn about the new optional chaining operator (?.) in JavaScript and its application in Vue.js Picture 1
As we know, to display the value of an object in Vue's template, we often use the text interpolation syntax {{}} as follows:
{{ data.user.name }}
However, the problem here is that in case the value we need to display is in a nested object, when a property before it does not exist, it will lead to an error, the template will not be displayed on the browser and the application will crash immediately.
In the above example, we want to display the 'name' value of the data object, but if the user property before it does not exist, the browser will throw an error Error in render: "TypeError: Cannot read property 'name' of undefined" .
The commonly used solution to display nested objects in templates without causing errors is to use Vue's v-if directive to check for the existence of properties in the nested object. For example, in the above example, we will put v-if on the template to check the data object, if the data object has a user property and the user has a name property, then the name value will be displayed on the browser:
{{ data.user.name }}
We see that the above solution can be convenient in the case where the nested object is only about one or two levels deep. In the case where the nested object is nested at multiple levels, we will have to write v-if conditions for multiple levels, as in the case below:
&& data.obj1.obj2
&& data.obj1.obj2.obj3
&& data.obj1.obj2.obj3.obj4'
>
{{ data.obj1.obj2.obj3.obj4}}
As you can see, our code will become verbose, difficult to follow, and possibly error-prone if we do not write the properties inside the object in the correct order. To overcome the above shortcomings, we can use a new operator of JavaScript, the ? operator. (Optional Chaining)
Learn about the new optional chaining operator (?.) in JavaScript and its application in Vue.js Picture 2
Introduction to the optional chaining operator (the ?. symbol)
Introduced in ES2020, the ?. operator helps solve the problem of accessing properties in an object even if the object or its properties do not exist. Typically, there are 3 syntaxes to use the ?. operator as follows:
- Used to access object properties:
For example: let abc = data?.obj.abc
- Used to access array properties:
For example: let abc = data?.[obj].abc
- Used to call an object's function even when it is uncertain whether the function exists or not:
For example: data.method?.()
Applying the ?. operator to the case of displaying nested objects in Vue's templates, we can write it concisely and safely as follows:
{{ data?.user?.name }}
The browser will no longer report the error Error in render: "TypeError: Cannot read property 'name' of undefined". However, in case the data or user property does not exist, we will see the undefined value displayed on the browser, which is not good for the user experience. To avoid this problem, we can set an empty value '' or some default value to replace undefined by adding that value after 2 ?? at the end of the nested object as follows:
- Set empty value ''
{{ data?.user?.name ??'' }}
- Set default value 'abc'
{{ data?.user?.name ??'abc' }}
When using a default value in the ?. operator, we see that the p tag is still rendered and displayed in Vue's template. There is a better way to use the ?. operator and Vue's v-text directive together. In the example above, the p tag will only be rendered and displayed in Vue's template when the value of the name attribute is not undefined or is set to a default value other than empty. It can be seen that v-text is a very good directive of Vue but is overlooked by many people.
Our above example would become.
Checking the browser, we see that in case the data object or user attribute does not exist, the browser does not report an error, the p tag will only render in case the name attribute has a specific value. The code becomes concise, easy to follow and safe. So clearly, we see that using the ?. operator with Vue's v-text directive to display the value of a nested object is a perfect combination.
Learn about the new optional chaining operator (?.) in JavaScript and its application in Vue.js Picture 3
Since the ?. operator is a fairly new operator, introduced in ES2020, some older browser versions from before 2019 may not support this operator. In addition, only Vue 3 currently supports this operator, so to be able to use this operator on Vue 2 and safely on older browsers, we need to configure Vue 2 as follows:
- First, install the vue-template-babel-compiler library to compile code using the ? operator. Run the command to install yarn add -D vue-template-babel-compiler
- Edit vue.config.js file, use vue-template-babel-compiler to help webpack compile
// vue.config.js file
module.exports = {
chainWebpack: config => {
config.module
.rule('vue')
.use('vue-loader')
.tap(options => {
options.compiler = require('vue-template-babel-compiler')
return options
})
}
}
Or can be configured in webpack.config.js file
// webpack.config.js
module: {
rules: [
{
test: /.vue$/,
loader: "vue-loader",
options: {
compiler: require("vue-template-babel-compiler"),
},
},
],
}
With the above configuration, we can use the ?. operator in Vue 2. In case we need to write unit tests using Jest for functions or Vue templates that use the ?. operator, we need to configure jest.config to be able to compile in the test environment as follows.
//jest.config.js file
module.exports = {
transform: {
'.*.(vue)$': 'vue-jest',
},
globals: {
'vue-jest': {
templateCompiler: {
compiler: require('vue-template-babel-compiler'),
transformAssetUrls: true,
},
},
},
}
Note: vue-jest version must be greater than or equal to 4.0.0 and jest less than or equal to 26.6.3.
Conclude
Although it is a bit cumbersome to configure to be able to use the ?. operator on Vue 2, we have more than enough reasons to do it because of the many benefits and outstanding advantages that the ?. operator brings to us when it is used in Vue as analyzed above.
You should read it
- Configure Web Proxy Chaining in Forefront TMG 2010 - Part 1
- What are the features of Windows 10 Windows Features?
- TypeScript optional parameters in Callbacks
- Windows 10 now allows users to update drivers for more devices through Windows Updates
- Paint and WordPad will become optional features on Windows 10 20H1
- What is 'Optional Quality Update' on Windows 10?
- How to install and remove optional features in Windows 11
- Stream in Node.js
- HP upgraded Dm4 to core i5
- Netbook weighs only 1kg, MSI's 15 hour battery
- Sony brings fashion to Vaio CS
- HP brought G-series laptops into Vietnam, priced from 13.3 million
May be interested
What is ActiveMQ? Benefits of ActiveMQ
What is NextJS? All the basic knowledge you should know
What is ReactJS? Why ReactJS is the future of web development
Next.js vs Express.js: Exploring the Differences Between the 2 Frameworks
Instructions on how to use the Grep command in Linux
What is Xcode and how to use it effectively