How to manipulate two data values in vue

Viewed 62

In Vue.JS I have

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

In my HTML I have

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

But the output is

Hi my name is {{name}}

The {{name}} isn't being replaced. I am taking this approach because the user can fetch different sentences from a db, so the name has to e dynamically changeable.

4 Answers

Define sentence as computed property :

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

or you could do that when you receive the data by using a regex :

data(){
   return {
         name: 'John',  
         sentence :  "Hi my name is {{ name }}"  
      };
   },
...
this.sentence = res.data.sentence.replace(/{{.*name.*}}/,this.name); 

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">
  {{ output }}
  
  <input type="text" v-model="newSentence" />
  <button @click.prevent="changeSentence()">Change</button>
</div>

Building ontop of Emīls Gulbis answer, Then you can update the value with a watcher when the sentence changes from the database like so:


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

You can't access data properties like {{name}} until the data method has returned, also {{this.name}} will return undefined.

To achieve that you need to use computed property:

computed:{
   sentence(){
     return  `Hi my name is ${ this.name }`
   }
}

Or

directly inside the template:

<h2>Hi my name is {{ name }}</h2>
Related