在 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/