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

标签 vue.js parent-child

我试图记住如何通过 parent 的:class绑定(bind)到模板中的特定子组件。例如:

// 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>
我是否需要为此目的创建一个新 Prop ?我可以从组件中访问 Vue 实例的特定部分吗?
谢谢

最佳答案

Do I need to create a new prop just for that purpose?


是的。 Vue 没有提供自定义类和样式属性如何应用于模板的方法。它将始终将它们应用于根元素,您无法更改它。
但是,如果它是一个功能组件,那么您可以这样做。但这不适用于这里。

Is there a specific part of the Vue instance I can access from within the component?


您可以直接从 vnode 访问该类:
this.$vnode.data.staticClass  // for class="static"
this.$vnode.data.class        // for :class="dynamic"

关于vue.js - Vuejs如何将父类传递给模板中的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64129495/

相关文章:

java - 创建返回子类对象的父类

C中通过管道进行通信

css - 防止子元素超过父元素的高度?

javascript - Vue - 是否可以动态设置 html 元素的样式?

javascript - 进入和离开时的 VueJS 转换

css - 如何在不激活父级悬停的情况下在子级中使用悬停?

c# - Unity - 如何从父游戏对象检测子对象的碰撞?

vue.js - 如何在 eslint-plugin-vue 中禁用 eslint?

javascript - 如何访问另一个子组件中的插槽内容

javascript - 无法将属性传递给 vue.js 中插槽中的组件?