How can I make the Vue component's class binding bind onto the inner element instead of the root element?

Suppose I have a very simple component that looks like this

Vue.component("my-component", {
  template: `
    <p class="foo bar">
      <span>Hi</span>
    </p>
  `,
});

If I use the component like this

<my-component class="baz boo"></my-component>

Final rendered HTML will look like this

<p class="foo bar baz boo">
  <span>Hi</span>
</p>

However, I want to bind my class onto the <span> tag instead of the root element.

This is the result I want

<p class="foo bar">
  <span class="baz boo">Hi</span>
</p>

How can I achieve this?

1 answer

  • answered 2021-01-11 05:26 Renato Manalili

    For me, you can pass it as props.

    <my-component :className="baz booz" />
    

    inside that component

    <span :class="class-name"> Hi </span>