1

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>

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

@Dakotha If this answer works for you, please mark it as accepted so that others with the same question know which answer to look at, and so our friend Grumaks gets credit for their good answer.
0

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.