gpt4 book ai didi

javascript - Vue : Use data to control DOM (but v-for, v-if、v-model 和 v-show 还不够)

转载 作者:行者123 更新时间:2023-12-02 23:08:13 26 4
gpt4 key购买 nike

我以前用过Vue,我知道怎么用v-for渲染元素序列,v-ifv-show有条件地显示元素,并且 v-model例如,控制段落的内容。

但现在我需要对 DOM 进行更精细的控制:

  • 我有一个ranges我的组件内的对象 data还有一个text我的模板中的 div ( text 可能是 id 和/或 ref 属性)。
  • 对于每个范围,我想突出显示text内文本的特定部分。 div 不是基于字符串或正则表达式匹配,而是基于文本索引(我之前使用 Rangy 执行过此操作)。
  • 我还想插入一些工具提示或弹出窗口,例如 v-tooltip在每个范围[可选]。

例如,我想突出显示 <div ref='text'>The cat chases a dog.</div> 中的当我的范围对象包含 { start: 0, end: 3 } 时.

在这种情况下,操作 DOM 对我来说不起作用,因为 (i) data 将会更新。导致 Vue 再次更新 DOM,删除之前的编辑和 (ii) 随后由类似 document.createElement('my-component'); 插入的元素Vue 甚至不将其识别为组件。

有什么方法可以利用 Vue 的数据驱动方法来完成我需要的事情吗?

最佳答案

当然,Vue 不支持附加 DOM,尝试这个。工作正常:

通过分割文本。我们得到了一个长度为 2 的数组

  1. 数组的第一部分 l[0] :是突出显示文本之前的文本
  2. 数组的第二部分 l[1] :是突出显示文本之后的文本

然后我们合并:l[0] + <p style="/* some style */"> + hightlighted_text + </p> + l[1]

然后我们使用 v-html 将 HTML 绑定(bind)到 div

You need to make some validation like : if highlighted text exists in whole text. if not, this will cause adding new text to the whole text.

var app = new Vue({
el: '#app',
data: {
words: '',
text: 'hello world im vue.js',
hightlighted: ''
},
methods: {
highlightMe() {
var l = this.text.split(this.words);
console.log(l);
this.hightlighted = l[0] + '<p style="background-color: red; display: inline">' + this.words + '</p>' + l[1];
}
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.4/vue.js"></script>

<div id="app">
<label>text to be highlighted :</label><br />
<input type="text" class="form-control" v-model="words"><br/>
<button @click="highlightMe">hightLight ` {{ words }} `</button>
<div>
{{text}}
</div>
<div v-html="hightlighted"></div>
</div>

关于javascript - Vue : Use data to control DOM (but v-for, v-if、v-model 和 v-show 还不够),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com