Vuejs如何将父类传递给模板中的子组件

时间:2020-09-30 00:51:58

标签: vue.js parent-child

我想记住如何将父级的:class绑定传递到模板中的特定子级组件。例如:

// parent-component.vue
<template>
  <child-component :class="['foo', bar, 'baz']">
</template>
// child-component.vue
<template>
  <div class="dont-want-classes-here">
    <h1 class="not-here-either">Someting v Important</h1>
    <sub-component :class="['want-parent-classes in-here', ...$parent.classes]">
  </div>
</template>

我是否需要为此目的创建一个新的道具?我可以从组件内部访问Vue实例的特定部分吗?

谢谢

1 个答案:

答案 0 :(得分:0)

我是否需要为此目的创建一个新道具?

是的。 Vue没有提供一种自定义如何将类和样式道具应用于模板的方法。它将始终将它们应用于根元素,并且您将无法更改。

但是,如果它是功能组件,则可以执行此操作。但这在这里不适用。

我可以从组件内部访问Vue实例的特定部分吗?

您可以直接从vnode访问该类:

this.$vnode.data.staticClass  // for class="static"
this.$vnode.data.class        // for :class="dynamic"