【问题标题】:Vue interpolation does not work in the text obtained by APIVue插值在API获取的文本中不起作用
【发布时间】:2019-11-22 16:48:24
【问题描述】:

通过 API 获取文本,文本中有 {{}} 中的实体,例如:

Some text {{rules}} other text

有数据值:

rules: "some text"

但是这个值没有插值,显示:

Some text {{rules}} other text

感谢回答

【问题讨论】:

  • 请分享您的代码。您在问题中包含的代码部分应该或不应该工作 - 取决于其他部分。请阅读:stackoverflow.com/help/how-to-askstackoverflow.com/help/minimal-reproducible-example,并重新表述您的问题。
  • 我有:模板:
    {{someText}}
    有数据:data() { return { someText:"some text {{ myValue }} some text", myValue: "300", } }, 如何在模板中显示来自 myValue 的数据?

标签: vue.js interpolation linear-interpolation


【解决方案1】:

考虑到上面的评论:

我有:模板:{{someText}} 有数据:data() { return { someText: "一些文本 {{ myValue }} 一些文本", myValue: "300", } }, 如何在模板中显示来自 myValue 的数据?

你不会在 Vue 中做这样的插值。双括号 ({{}}) 用于 模板 部分,而不是脚本。

看看这个sn-p:

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>

我在parsedSomeText() 计算属性 中创建了一个小型解析器,它非常粗略地替换了someText 数据属性中的双括号并返回修改后的字符串,以便让它在数据 属性。

我建议您查看收到的数据,并考虑另一种解决方案 - 或利用一些坚如磐石的解析技术在生产中使用它。

如果您无法避免以这种方式获取数据,那么您应该研究动态(运行时)编译(如:https://alligator.io/vuejs/v-runtime-template/)和渲染函数(https://vuejs.org/v2/guide/render-function.html)。有了这些,您的 Vue 应用程序变得更加通用但更加复杂。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2022-11-11
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多