vuejs 2 v-for :key 不起作用,html 被替换了? [英] vuejs 2 v-for :key not working, html being replaced?
问题描述
我正在 v-for 中渲染一些 HTML
I'm rendering some HTML in a v-for
但是每次我更改任何数据时,我所有的 html 都会被替换(输入字段会丢失它们的值)
But everytime I change any of the data, all my html gets replaced (input fields lose their values)
我尝试给 :key 赋予各种不同的值
I tried giving the :key all kinds of different values
我在 vue v1 中没有这个问题,只有在 v2 中
I didn't have this problem in vue v1, only in v2
http://jsbin.com/jomuzexihu/1/edit?html,js,输出
推荐答案
我有一点玩这个,看起来 Vue 在使用 <input/> 时没有重新渲染整个列表code> 或者如果您使用
component
但它使用 v-html
.这是比较的小提琴:
I had a little play with this and it appears that Vue does not re-render the entire list when using <input />
or if you use a component
but it does with v-html
. Heres the fiddle for the comparison:
https://jsfiddle.net/cxataxcf/
这里实际上不需要密钥,因为列表没有被重新排序,所以您的问题与 :key
无关,而是与 v-html<有关/代码>.以下是文档关于
v-html
的说明:
The key actually isn't needed here because the list isn't being re-ordered, so your issue isn't to do with :key
but rather with v-html
. Heres what the docs say about v-html
:
内容作为纯 HTML 插入 - 数据绑定被忽略.请注意,您不能使用 v-html 来组合模板部分,因为 Vue 不是基于字符串的模板引擎.相反,组件更适合作为 UI 重用和组合的基本单元.
The contents are inserted 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. Instead, components are preferred as the fundamental unit for UI reuse and composition.
所以我想这就是问题所在.
So I guess this is where the problem lies.
可能值得在 Vue 的 github 页面上提出一个问题,看看这是否是 v-html
的预期行为,但 Vue 2.0 比 vue 1.x 和似乎不建议使用 v-html
,因此可能只是您需要重构代码以改用组件.
It might be worth raising an issue on Vue's github page to see whether this is the expected behavior for v-html
, but Vue 2.0 is much more heavily focused on components than vue 1.x and doesn't appear to recommend using v-html
, so it may just be that you need to re-factor your code to use components instead.
编辑
解决这个问题的方法是简单地将代码包装在一个组件中,并将 HTML 作为 prop 传递:
The solution to this problem is to simply wrap the code in a component and pass the HTML as a prop:
Vue.component('unknown-html', {
props: {
html: ""
},
template: '<div><div v-html="html"></div>'
})
标记:
<unknown-html :html="thing.html"></unknown-html>
和视图模型:
var app = new Vue({
el: '#app',
data: {
numInputs: 1,
stuff: [{
'html':'<input />'
}, {
'html':'<button>Foo</button>'
}]
}
})
这是 JSFiddle:https://jsfiddle.net/wrox5acb/
Here's the JSFiddle: https://jsfiddle.net/wrox5acb/
这篇关于vuejs 2 v-for :key 不起作用,html 被替换了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!