[Vuejs]-Vue interpolation does not work in the text obtained by API

0👍

Considering the comment above:

I have: template: {{someText}} have data: data() { return {
someText: "some text {{ myValue }} some text", myValue: "300", } },
How display data from myValue in template?

You don’t do interpolation like that in Vue. Double braces ({{}}) are for the template part, not the scripts.

Look at this snippet:

new Vue({
  el: "#app",
  data() {
    return {
      someText: "some text {{ myValue }} some text",
      myValue: "300"
    }
  },
  computed: {
    parsedSomeText() {
      let ret = ''
      if (/(\w+)(?= }})/g.test(this.someText)) {
        let key = String(this.someText).match(/(\w+)(?= }})/g)[0]
        if (Object.keys(this.$data).includes(key)) {
          ret = this.someText.replace(/{{ (\w+) }}/g, this.$data[key])
        }
      }
      return ret
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  myValue: {{myValue}}<br /> someText: {{someText}}<br />parsedSomeText: {{parsedSomeText}}
</div>

I created a small parser in parsedSomeText() computed property, that very crudely replaces the double braces in the someText data property and returns the modified string, so to get it working in the data property.

I advise you to look over the data you receive, and think of another solution – or utilize some rock-solid parsing technique to use it in production.

If you cannot avoid getting data in such a way, then you should look into dynamic (run-time) compilation (like: https://alligator.io/vuejs/v-runtime-template/) and render functions (https://v2.vuejs.org/v2/guide/render-function.html). With these, your Vue app becomes more versatile but more complex.

Leave a comment