Home > Article > Web Front-end > Do you need to use square brackets for variables in Vue?
Do I need to use square brackets for variables in vue?
In Vue.js, we often need to render variables into templates. When we want to render a variable into a template, we have different ways to do it. One way is to use square brackets to encapsulate the variable, and the other way is to use ES6 template strings.
Use square brackets to encapsulate variables:
In the Vue.js template, using double curly brackets to wrap the variable can bind the variable to the template, so that data changes can be automatically Update view. If brackets are used to wrap a variable, the variable will be interpreted as a JavaScript expression and automatically evaluated, and the result of the evaluation will be rendered into the template.
For example, when we need to render a variable "message" into the template, we can write like this:
<template> <div>{{ message }}</div> </template>
In this example, we use double curly braces to wrap the variable "message ”, Vue.js will bind this variable to the template and automatically update the view.
If we use square brackets to wrap the variable, for example:
<template> <div>[{{ message }}]</div> </template>
Then the variable "message" will be interpreted as a JavaScript expression and will be automatically evaluated, and the result after evaluation will be is wrapped in square brackets and rendered into the template.
Use ES6 template strings:
In addition to using square brackets to encapsulate variables, we can also use ES6 template strings to render variables. A template string is a string defined using backticks (`), in which variables can be used, and can contain multiple lines of text.
For example, when we need to render a variable "message" into a template, we can write like this:
<template> <div>{{ `My message is ${message}` }}</div> </template>
In this example, we use the ES6 template string to wrap the variable "message", use ${} to insert variables. This way the variables can be rendered into the template.
Summary:
In Vue.js, using square brackets to encapsulate variables and using ES6 template strings are both effective ways to render variables into templates. Using square brackets to encapsulate variables is a syntactic sugar of Vue.js, which allows us to render variables more conveniently. Template strings using ES6 are a regular JavaScript syntax and can use more string manipulation functions. No matter which method is used, it will not affect the normal rendering function of Vue.js.
The above is the detailed content of Do you need to use square brackets for variables in Vue?. For more information, please follow other related articles on the PHP Chinese website!