我有一个文本,里面有链接。但是我在渲染 View 后添加这些链接( anchor 元素)(我从服务器获取链接信息并为每个单词插入 anchor 元素)。每个链接都调用容器内的函数,但我猜因为链接在渲染后插入到页面中,所以它们不会绑定(bind)到模型方法。如何在渲染后将这些链接点击事件绑定(bind)到该方法?
这是我的组件:
<div class="info-text" v-html="descriptionShown"></div>
最佳答案
不幸的是,你不能这样做。 Vue 的 v-html 指令将内容绑定(bind)为原始 HTML,而不是像您通常使用的 vue 模板语法,这意味着 vue 不会解释任何数据绑定(bind),例如事件。来自 vue 指南:
The contents of the span will be replaced with the value of the rawHtml property, interpreted as plain HTML - data bindings are ignored. Note that you cannot use v-html to compose template partials, because Vue is not a string-based templating engine.
此外,通常认为应该避免这种情况,因为这会使您的网站容易遭受 XSS 注入(inject),除非您非常小心如何使用 v-html 属性并确保它永远不会触及用户输入的内容。
最好的选择是根据需要将数据解析为对象或数组,并由具有 v-for 循环或类似循环的组件处理,数据作为 prop 传递。 例如。你可能有这样的东西:
[{text: "Some text content", link: ''},{text: "Followed by a link.", link: "example.com"}]
让组件使用 v-for 对其进行操作,然后根据链接内容或您想要定义的任何其他属性生成纯文本或 anchor 标记,例如使用 $emit 发出特定事件('eventName') 您可以捕获调用组件的位置。
关于javascript - 组件渲染后,Vue.js 将 click 事件绑定(bind)到 v-html 内的 anchor 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69232907/