Vue Js concat string and variable:In Vue.js, you can concatenate a string and a variable using template literals or string interpolation. Template literals allow you to embed expressions inside backticks () and use ${} syntax to insert variables. For example:
Hello ${name}` would concatenate the string “Hello ” with the value of the variable ‘name’. String interpolation is another approach where you use the + operator to concatenate the string and variable. For example: “Hello ” + name. Both methods achieve the same result of combining a string and a variable in Vue.j
How can I concatenate a string and a variable in Vue.js?
In the provided Vue.js code, a string and a variable are concatenated using template literals. The message
computed property displays a greeting message by combining the string “Hello, ” with the value of the name
variable. Similarly, the concatenatedString
computed property combines the values of the name
and age
variables to create a sentence about the person’s name and age. The resulting strings are displayed within the <p>
tags in the HTML template.
Vue Js concat string and variable Example
<div id="app">
<p>{{ message }}</p>
<p>{{ concatenatedString }}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
name: 'John',
age: 30
};
},
computed: {
message() {
return `Hello, ${this.name}!`; // Concatenating a string and a variable
},
concatenatedString() {
return `My name is ${this.name} and I am ${this.age} years old.`; // Concatenating multiple variables
}
}
});
</script>