【问题标题】:Vue - Passing inline css style to child componentVue - 将内联 css 样式传递给子组件
【发布时间】:2021-08-30 07:06:36
【问题描述】:

我正在使用 vue.js + vuetify,我必须在画布组件上放置一个按钮(此处由 Konva 库处理)

我通过使用按钮的绝对定位来管理它。 为了清理,我想将此按钮放在一个专用组件中。

我想将定位 css 内联传递给这个新的子组件,但不知道如何使它工作。

我尝试了以下两种方法

  • 使用 :style="xxx" 绑定传递它,就像我直接使用 v-btn 时所做的那样
  • 将定位传递给父 div:与宽度为 != 0 的 div 一起使用,但看起来像个杂物。在这种情况下,z-index 不会应用于按钮。
  • 我可以使用专用道具传递属性,但 vuetify 似乎不需要它

这基本上是我的代码:

<template>
  <v-container fluid fill-height ref="parentLayout" class="pa-0" :style="{position: 'relative'}">
    <!-- Konva area overwhich the button will be placed drawn over /-->
    <div ref="konvaLayout" :style="{backgroundColor:'rgb( 40, 40, 40 )'}">
      <!-- THIS WORKS /-->
      <v-btn absolute :style="{top:'10%', left:'10%', width: '100px'}"> THIS WORKS </v-btn>
      <!-- THIS DOES NOT /-->
      <my-button :style="{position: absolute, top:'2%', left:'2%'}" />
  </v-container>
</template>

总结一下我有以下两个问题:

  1. 如何像 vuetify 一样正确地将 :style 绑定到子元素?
  2. 将 css 位置属性传递给子组件的标准方法是什么?像 1) 这样的样式绑定?

谢谢大家的帮助

【问题讨论】:

    标签: javascript vue.js vuetify.js


    【解决方案1】:

    在这种情况下的问题基本上是 v-deep 在 css 世界中应该解决的问题(虽然这不会解决你的问题)

    konvaLayout div 中没有 native 元素,因此样式不会到达目标组件。

    在MyButton.vue 组件中,您有两个选项可以解决这个问题:

    - style 道具覆盖 -

    //MyButton.vue
    <template>
      <v-btn :style="style">{{ label }}</v-btn>
    </template>
    
    <script lang="ts">
    import { defineComponent } from 'vue';
    
    export default defineComponent({
      props: {
        label: String,
        style: [String, Object]
      }
    });
    </script>
    

    - 自定义道具 -

    您使用了专门用于设置my-button 中按钮样式的自定义道具名称(哈哈)

    //MyButton.vue
    <template>
      <v-btn :style="btnStyle">{{ label }}</v-btn>
    </template>
    
    <script lang="ts">
    import { defineComponent } from 'vue';
    
    export default defineComponent({
      props: {
        label: String,
        btnStyle: [String, Object]
      }
    });
    </script>
    

    (没有保证,因为我们没有提供代码和类似的东西来验证它是否工作)

    【讨论】:

    • 感谢您的回答!基于它,我选择了我命名为样式的专用自定义道具。覆盖 style 属性在我这边触发了一个 vue 警告。附加说明:传递 :style 绑定有效,但前提是我的按钮是我的子组件的根元素。
    • 很高兴我能帮上忙。事件如果它只是正确的方向
    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 2017-12-02
    • 2019-01-24
    • 2018-09-14
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多