关于vue3的inheritAttrs属性和$attrs的部分用法


当我们在父组件中想要为子组件的某一个标签添加一些样式(注意,这里的是指attributes,css样式只是其中一种属性而已)

 <show-message id="lkx" class="lkx" title="HHH" content="123">show-message>

如果不做任何设置,那么子组件被渲染出来是这样的

 他会在子组件的根标签上添加样式,这显然不符合我们的需求,所以我们在子组件添加该属性



inheritAttrs:false,

此时浏览器渲染结果为



 看不到任何的样式加载了,这时我们可以在想要添加的子组件某一标签的样式处添加:class="$attrs.class"



<template>
<div>
<h2 >{{title}}h2>
  <h2 :class="$attrs.class">{{content}}h2>
  <h2>{{info.msg}}h2>
div>
template>
这样就可以将想要的样式添加到想要的标签上啦,渲染后的结果如下

 当然,如果父组件有id和class,可以使用:="$attrs"优化一下写法,v-bind = "$attrs"

<div>
<h2 >{{title}}h2>
  <h2 :="$attrs">{{content}}h2>
  <h2>{{info.msg}}h2>
div>

结果如下