Dakotha
Dakotha

Reputation: 11

VueJS: How to inject a variable to a text from API

I get some text from API then I display it. But before I display it, I need to inject or replace some variable in the text to value from variable.

Please check this out to understand what I mean:

https://jsfiddle.net/0q4ot5sw/

new Vue({
  el: "#app",
  data: {
    text: 'Some very long text from API where I need to inject %variable%',
    variable: 'some word' // How to inject this variable to the text?
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  {{ text }}
</div>

Upvotes: 1

Views: 1059

Answers (3)

Alexis Pavlidis
Alexis Pavlidis

Reputation: 1080

You can create a function (or a computed property, this decision is actually yours) and combine those two strings. Something like this

new Vue({
   el: "#app",
   data: {
     text: 'Some very long text from API where I need to inject',
     variable: 'some word'
   },
   methods: {
     getText: function(){
       return this.text + this.variable;
     },
     toggle: function(todo){
       todo.done = !todo.done
     }
   }
})

On your template, you just call the function you created

<div id="app">
  {{ getText() }}
</div>

Upvotes: 0

sandeep balaji
sandeep balaji

Reputation: 36

You can use computed value to do the task

new Vue({
  el: '#app',
  data: {
    text: 'Some very long text from API where I need to inject',
    variable: 'some word123' // How to inject this variable to the text?
  },
  computed : {
  	changeText : function() {
    	return this.text + this.variable
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ changeText }}</p>
</div>

Upvotes: 0

Grumaks
Grumaks

Reputation: 159

You can do that

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  {{ text.replace("%variable%", variable) }}
</div>

or that

new Vue({
  el: "#app",
  data: {
    text: 'Some very long text from API where I need to inject %variable%',
    variable: 'some word' // How to inject this variable to the text?
  },
  computed: {
    resultText: function() {
      return this.text.replace("%variable%", this.variable);
    }
  }
})
and use like this

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  {{ resultText }}
</div>

Upvotes: 1

Related Questions