Tips for altering dual data values in Vue

When working with Vue.JS, I encounter the following situation:

data() {
  return {
     name: 'John',
     sentence: "Hi, my name is {{ name }}",
  };
},

In my HTML file, I have the following line:

<h2>{{ sentence}}</h2>

However, when viewing the output, I see:

Hi, my name is {{name}}

The issue here is that the {{name}} placeholder is not being replaced. The reason for this approach is to allow dynamic updates from a database where different sentences can be fetched and the name needs to be interchangeable.

Answer №1

Declare sentence as a computed property :

data(){
   return {
         name: 'Alice',      
      };
   },
computed:{
   sentence(){
     return  `Hello, my name is ${ this.name }`
   }
}

Alternatively, you can modify the data with a regex when it is received:

data(){
   return {
         name: 'Alice',  
         sentence :  "Hello, my name is {{ name }}"  
      };
   },
...
this.sentence = resp.data.sentence.replace(/{{.*name.*}}/,this.name); 

Answer №2

let vueInstance = new Vue({
  el: "#app",
  data() {
    return {
      name: 'John',
      sentence: 'Hi my name is {{ name }}',
      newSentence: 'Thanks {{ name }}!'
    }
  },

  computed: {
    output() {
      return this.sentence.replace(/{{.*name.*}}/, this.name)
    }
  },
  
  methods: {
   changeSentence() {
      this.sentence = this.newSentence
      this.newSentence = 'try anything {{ name }}'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ vueInstance.output }}
  
  <input type="text" v-model="vueInstance.newSentence" />
  <button @click.prevent="vueInstance.changeSentence()">Change</button>
</div>

Answer №3

Accessing data properties like {{name}} can only be done after the data method has returned. Similarly, using {{this.name}} will result in undefined.

To resolve this issue, you can utilize a computed property:

computed:{
   phrase(){
     return  `Hello, my name is ${ this.name }`
   }
}

Alternatively, you can directly include it inside the template:

<h2>Hello, my name is {{ name }}</h2>

Answer №4

To expand on Emīls Gulbis' response, one approach is to utilize a watcher to update the value when the sentence changes in the database:


  watch: {
    sentence(newSentence) {
      this.sentence = newSentence.replace('{{ name }}', this.name)
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Anticipate the striking impact of Tapestry in JavaScript

Our app uses Tapestry 5.3.8, and Selenium 2.53.1 for integration tests. There are times when a Selenium test needs to wait for an action to complete, such as when Tapestry initiates an AJAX request. In such cases, the following code is used to wait for th ...

What steps can be taken to make the carousel inconsistent when relying on the assigned id in props?

I recently developed a slider with slots, but encountered an issue. The code for this component revolves around the use of IDs for each slide as prop, making it unnecessarily complex. I am convinced that there is a more straightforward way to achieve the s ...

The loading time for the Ajax request is unreasonably slow

I am currently managing a website dedicated to League of Legends. My main task involves requesting statistics from the Riot Games API based on a player's name, which returns the information in JSON format. However, there is a significant delay in load ...

What is the reason my CSS formatting isn't being applied in Vue.js?

As a newcomer to web development and vue.js, I've been struggling to style my code effectively. Below is an example of my vue.js code where I have created markup for a profile description using figure, figcaption, and image elements. Could you please ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

Generating an associative array on the fly

I am interested in transforming a hash by creating nested keys and then adding another hash at the end. For example... var hash_a = {'foo': 'bar'} var hash_b = {'alpha': 'beta'} var array = ['a', 'b& ...

How can you replicate a mouseover event using Selenium or JavaScript?

I have recently been working on a task involving web UI automation using Selenium, Javascript and SeLion. My goal is to capture a screenshot of a scenario similar to the Google homepage, specifically focusing on the "Search by voice" feature when hovering ...

Can you provide an example of JSON for a MultiStep Form that includes a variety of control types for viewing

Could someone please provide me with JSON examples of multi-step forms that include various types of controls such as radio buttons, checkboxes, dropdown menus, and calendars? I am in need of JSON for both the view and edit forms. Your help would be grea ...

Setting references to child components with VueRouter in Vue

I've written the following code snippet in my main.js file for my Vue web application: const routes = { name: "Main", path: "/main", redirect: "/main/home", component: MainComponent, children: [ { path: &quo ...

Is it possible to turn off Vue warnings for a particular component?

In my Vue application, I have a parent component that includes its own on-screen keyboard, which is a separate Vue component. This keyboard tracks the entered value and sends it to the parent component. Sometimes, the parent component needs to reset this v ...

Setting up GameClosure on a Windows machine

Is it possible to install GameClosure on Windows? The installation guide mentions that only OSX is officially supported, but there have been reports of success running it on Linux and Windows. However, the process for doing this is not well-documented. A ...

Maintain consistent theme across various pages using javascript

So I successfully implemented a dark mode on the front page using the following script (sourced from W3schools) : <script> function darklightmode() { var element = document.body; element.classList.toggle("dmode"); } </script> ...

Discover the method to calculate the combined file size of multiple uploads with jquery

One of the challenges I'm facing is ensuring that users can only upload multiple files if the total size does not exceed 3GB. Is there a way I can enforce this limit? Below is the current code snippet I am using: var fileCount = 0; var showFileCo ...

The Null object within localStorage is identified as a String data type

As someone transitioning from Java development to Javascript, I am seeking clarification on a particular issue. In my project, I am utilizing localStorage to keep track of the user's token in the browser. localStorage.token = 'xxx' When a ...

Heroku is rejecting the Discord token, but it is functioning properly in Visual Studio Code

I am facing an issue with an invalid token error on Heroku, even though the token in my main.js file on Git is the same as the one I have in Visual Studio Code. Interestingly, Heroku claims it's an invalid bot token while the Discord bot token from VS ...

Incorrect interpretation of JavaScript object

To display some structured data on my JADE page, I created a JSON-like object containing variables, text, and JavaScript objects. Here is an example of what the JSON object looks like: var dataSet1 = { meta: { "name": "Some text", "minimum": mini_ ...

Unmounting a Vue3 component in the script setup: A step-by-step guide

Let's say we have a component structured like this. <template> <el-card @click='destroyCard'> ...... </el-card> </template> <script setup> ...... let destroyCard = () => { ...... } onUnmoun ...

Encountering an unexpected issue with $urlMatcherFactory during an AngularJS service unit test

I am seeking guidance on writing a proper unit test for a service using the jasmine framework and karma as the test runner. Below is the implementation in example-service.js: export default class ExampleService { constructor($resource, $http, $urlMatcher ...

Verification of three-dimensional password format with the use of AngularJS

I am trying to implement password validation in Angular.js that requires a combination of alphabetical, numerical, one upper case letter, one special character, no spaces, and a minimum length of 8 characters. How can I achieve this using Angular.js? Here ...

Issue with parsing an empty array in a Discord bot built with Node.js

Within this API, there exists an empty array marked with a red underline. Sometimes it's void of content, but other times it contains data. My goal is to display Item Spells: there are no effects on this item. when the array is empty. However, instead ...