Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【如何避免vue在组件上使用v-bind="{}"指令使用时, 组件将没有声明的属性渲染到了元素上】 #59

Open
kind-hearted opened this issue Sep 21, 2018 · 0 comments

Comments

@kind-hearted
Copy link
Owner

kind-hearted commented Sep 21, 2018

vue运行时将v-bind的指令绑定的值放到createElement函数的data参数的attrs属性上 data = { attrs: { } },如果绑定的是一个对象,会将对象展开到attrs里面,attrs里面的属性会被渲染到真实的元素上,在创建组件的时,会将组件声明过的属性从attrs提取掉(extractPropsFromVNodeData),除去一些特殊属性外,剩下的属性会被渲染到元素上。

在使用过程中,我们会碰到这种情况一个对象,而对象上的属性有可能是组件内没有声明的,这些属性都会渲染到元素上。怎么处理?

可以修改源码的extractPropsFromVNodeData,在其return res前添加以下代码

// 在提取完prop以后, 删掉特殊属性外的key, 避免渲染到元素上, data-这种data-set属性也保留
var special = ['key', 'ref', 'slot', 'slot-scope', 'scope', 'is', 'style'];
if (isDef(attrs)) {
  for (var key in attrs) {
    if (special.indexOf(key) === -1 && key.indexOf('data-') === -1) {
      delete attrs[key]
    }
  }
}

当然,直接修改源码的方式,风险比较大,只是提供一种思路。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant