使用自定义的vue组件,如何在使用时设置组件内部的指定元素的外观?

我开发一个组件,组件内部有一些元素,给该这些元素默认的style,或者class(在vue文件内设置)。

我以后要使用该组件的时候,可能要改变组件内的某些元素的外观显示,但不想进入组件vue文件修改,我想直接在使用它的父组件的文件内修改外观显示。想使用类似设置style的配置方式,这样比较便捷

比如自定义组件,内部有一个<button style="color:red,bgcolor:black">{{title}}</button>和其他元素。该组件内部的button元素绑定了内部的事件

使用该自定义组件时,直接在父组件修改,该自定义组件内部的button的外观显示,这个怎么做?

一种方式,使用json设置style,通过prop传入子组件,但这个配置感觉不如使用css方式那样方法。有其他的方法吗?使用类似css或设置html标签的style的配置方式

回复
阅读 419
2 个回答

子组件使用插槽, button传进去: https://cn.vuejs.org/guide/components/slots.html#slots

image.png

<template>
  <slot></slot>
</template>


<script>
export default {
  mounted () {
    document.querySelector('#button').addEventListener('click', () => {
      console.log("点击了");
    })
  }
}
</script>

image.png

给组件传入一个自定义 class 的prop

// child
<div :class="[ 'child', customClass ]">
    <button>你好</button>
</div>

<script setup>
const props = defineProps({
    customClass: {
        type: String,
        default: ""
    }
});
</script>

// parent
<Child custom-class="my_class" />
推荐问题
宣传栏