在VueJS中用可点击的HTML元素替换字符串

ntjbwcob  于 2023-03-19  发布在  Vue.js
关注(0)|答案(1)|浏览(177)

对于文档编辑器工具,我需要用可点击元素替换字符串,这样用户就可以为这些变量输入正确的值。例如(“$Year”&“$SomeName”):
中的印刷和排版行业的简单虚拟文本存有一直是行业的标准假人文本自从**$年一个未知的打印机采取了类型的厨房和炒它做一个类型的标本书$SomeName}**。它不仅存活了五个世纪,但也eap成电子排版,保持基本不变。
我可以使用正则表达式来查找和替换$Variable字符串。
然而,我想用React式html元素替换字符串(例如),这样我就可以将它们绑定到我的Vue组件中的方法,如下所示:

<span @click="showVariablePopup('SomeName')">$SomeName</span>

当然,如果我只是用上面的代码替换这些变量字符串,并像这样显示html,这是行不通的:

<div v-html="stringWithReplacements"></div>

有什么办法能让我做到吗?

t1qtbnec

t1qtbnec1#

下面是一个简单的解决方案,文本被解析为文本节点和变量节点,然后你可以打印文本节点,并对变量节点做任何你想做的事情:

const text = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the $Year an unknown printer took a galley of type and scrambled it to make a type specimen book $SomeName}. It has survived not only five centuries, but also the eap into electronic typesetting, remaining essentially unchanged.`

const parseText = (text) => {
  const parts = []
  while (text) {
    const nextVarIx = text.search(/\$\w+/)
    if (nextVarIx === -1) {
      parts.push({
        text
      })
      break
    }
    if (nextVarIx > 0) {
      parts.push({
        text: text.substring(0, nextVarIx)
      })
      text = text.substring(nextVarIx)
    }
    const varEnd = 1 + text.search(/\w\b/)
    const variable = text.substring(0, varEnd)
    parts.push({
      variable,
      value: '<Click to change>'
    })
    text = text.substring(varEnd)
  }
  return parts
}

new Vue({
  el: '#app',
  methods: {
    fill(variable) {
      variable.value = (Math.random() + 1).toString(36).substring(7)
    },
  },
  data() {
    return {
      textData: parseText(text),

    };
  },
})
.text-variable {
  font-weight: bold;
}
.text-variable:hover {
  cursor: pointer;
}
<div id="app">
  <div>
    <template v-for="(part, index) in textData" :key="index">
      <span v-if="part.variable" class="text-variable" @click="fill(part)">
        {{ part.value }}
      </span>
      <span v-else>{{ part.text }}</span>
    </template>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.10/vue.min.js"></script>
<script src="https://unpkg.com/v-calendar"></script>

相关问题