【问题标题】:How to avoid VueJS to remove the props attributes in the DOM?如何避免 VueJS 移除 DOM 中的 props 属性?
【发布时间】:2016-08-03 08:43:38
【问题描述】:

我在正确传递给组件的组件上有一个prop。该值在组件内正确设置。但是该属性在 VueJS 的编译时被删除。 (我猜)

如何避免属性被删除?在运行时,我需要能够获取具有相同属性的每个元素,例如:$("[group-name=' + vm.groupName + ']");

这是DEMO

HTML

<script type="x-template" id="my-component-tpl">
  <div>My Component's group name is <b>{{groupName}}</b>.</div>
  <div>But the attribute 'group-name' is no longer in the DOM...</div>
</script>

<div id="app">
  <my-component group-name="Demo"></my-component>
</div>

JS

var myComponent = {
  template: '#my-component-tpl',
  props: ['groupName']
};

new Vue({
  el: '#app',
  components: {
    'my-component': myComponent
  }
});

【问题讨论】:

  • 为什么要在 dom 中使用它?
  • @gurghet 如问题中所述:“我需要能够获取具有相同属性的每个元素,例如:$("[group-name=' + vm.groupName + ']");

标签: javascript html vue.js


【解决方案1】:

除了我个人认为您应该使用具有某些非标准属性的类这一事实之外 - 您必须再次将其添加到模板中的根元素中。

<script type="x-template" id="my-component-tpl">
  <div v-bind:group-name="groupName">
    My Component's group name is <b>{{groupName}}, and the outer div also has the correspondign attribute now.</b>
   </div>
</script>

【讨论】:

  • 我想我必须去做这样的事情。 =/ 我不能使用类,因为元素可以有任何group-name 并且可能有多个类名。这会让人很难猜测要使用哪个类。
【解决方案2】:

我解决了你的问题。 (实现@LinusBorg 所说的)

http://jsfiddle.net/gurghet/8xwm9LmL/1/

附带说明:请记住,当您设置 replace: true(这是默认设置,因此,如果您设置它,则将其设置为 true)您是在告诉 Vue替换您的组件,在这种情况下 &lt;my-component&gt;...&lt;/my-component&gt; 用您的组件。如果您不喜欢这种行为,请设置replace: false

【讨论】:

  • replace 属性值得牢记,谢谢!尽管我相信,无论如何,它使 DOM 使用组件看起来有点损坏。
猜你喜欢
  • 2020-07-01
  • 1970-01-01
  • 2019-06-21
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 2017-11-29
相关资源
最近更新 更多