首页 > 解决方案 > Vuejs如何将父类传递给模板中的子组件

问题描述

我试图记住如何将父级的: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 实例的特定部分吗?

谢谢

标签: vue.jsparent-child

解决方案


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

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

但是,如果它是一个功能组件,那么您可以这样做。但这不适用于这里。

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

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

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

推荐阅读