javascript - Vue中添加 "v-on"的内容如何设置 "v-html"

标签 javascript vue.js vuejs2

在 Vue 中是否可以在 v-html 中添加的字符串上添加 v-on 事件? 在示例中,单击“Maggie”链接时没有任何反应。它似乎没有在 Vue 中注册。

或者也许还有另一种方法可以做到这一点? 我正在使用 Vue.js 2.1.3

Javascript

window.onload = function() {
    new Vue({
        el: '#app',
        data: {
            users: ['Homer', 'Marge', 'Bart', 'Lisa', '<a href="#" v-on:click="click_user">Maggie</a>']
        },
        methods: {
            click_user: function() {
                console.log('Click user')
            },
        }
    })
}

HTML

<div id="app">
    <div v-for="user in users" v-html="user"></div><br>
    <a href="#" v-on:click="click_user">This works.</a>
</div>

最佳答案

来自vue docs :

Updates the element’s innerHTML. Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates. If you find yourself trying to compose templates using v-html, try to rethink the solution by using components instead.

这意味着 v-on 不会在 v-html 中工作,因为它需要 vue 才能工作。


您的特定问题的潜在解决方案

有条件地使用 v-if 呈现链接,否则呈现纯文本。

new Vue({
  el: '#app',
  data: {
    users: [
      { name: 'Homer', clickable: false },
      { name: 'Marge', clickable: false },
      { name: 'Bart', clickable: false },
      { name: 'Lisa', clickable: false },
      { name: 'Maggie', clickable: true },
    ]
  },
  methods: {
    click_user: function() {
      console.log('Click user')
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.0/vue.js"></script>

<div id="app">
  <div v-for="user in users">
    <div v-if="!user.clickable">{{user.name}}</div>
    <a v-if="user.clickable" href="#" v-on:click="click_user">{{user.name}}</a>
  </div>
</div>

关于javascript - Vue中添加 "v-on"的内容如何设置 "v-html",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020059/

相关文章:

vue.js - vue 外部函数,将数据传入 vue

javascript - 当我将某个项目更改为垃圾箱时,为什么我的本地存储不会更新?

javascript - WebGL 创建纹理

html - 如何让 Nuxt.js 预渲染页面的完整 HTML?

vue.js - Vuejs Axios 数据未显示

vuejs2 - 默认选择选项未在 DOM 中更新,即使 v-model 属性正在更新

javascript - 如何使用正则表达式转换文本中的表情符号?

javascript - 检测 Canvas 文本 API 支持(Opera Mini)

javascript - Vuejs : How to display selected <li> element in ul dropdown menu

javascript - Vuejs 动态添加 ref undefined