Search code examples
javascriptvue.jsvuejs2data-bindinghyphenation

What is the purpose of hyphenated attribute naming and how it works?


I am creating a component (vue 2.6) and just realised that if the attribute class is not hyphenated actually doesn't deliver the string to the component. And other attributes with no hyphenated names do deliver their values. This is how my code looks like:

Component:

<template>
  <video
    controls
    :class="cssClass"
  >
    <source :src="videoSource" type="video/mp4"/>
  </video>
</template>

<script>
export default {
  name: 'VideoComponent',
  props: {
    videoSource: { type: String, default: '' },
    cssClass: { type: String, default: '' },
  },
};
</script>

How I am using it:

<VideoComponent
  v-if="selectedAsset.type == 'video'"
  css-class="cssClassName"
  :videoSource="selectedAsset.videoSource"
/>

So if I name the attribute cssClass and not css-class when I am using it in the father component, VideoComponent does not receive it and is empty BUT videoSource works fine... Why it works with some attributes and the others not?

To use same naming for attributes and properties when I use a component.


Solution

  • VideoSource is an object, so it will be passed as an object directly to your src prop.

    As for the props, there is a convention: https://vuejs.org/style-guide/rules-strongly-recommended.html#prop-name-casing

    Follow it: css-class (kebab-case) for the prop when passing it to a component, and cssClass (camelCase) when receiving it in the child component.

    EDIT: it should of course be :css-class aka v-bind:class-css otherwise it is not passed as a reactive object but as a regular string.

    Vue devtools can help you here.