vue.jsvuejs3vue-componentvue-props

Passing static data from parent to child Vue component


I'm studying Vue.js online through YouTube videos and I learned that to pass data from a parent to a child component we use v-bind in the parent and props in the child, yet after I created my first project with the CLI using vue create my-app, I'm stuck with this snippet in the generated code:

in App.vue

<HelloWorld msg="Welcome to Your Vue.js App"/>

in HelloWorld.vue

<template>
  <div class="hello">
    <h1>{{ msg }} </h1>
  </div>
</template> 

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  }
}
</script>

Shouldn't it be <HelloWorld v-bind:msg="Welcome to Your Vue.js App"/>?


Solution

  • In Vue.js, you can omit the colon (:) when you're not passing a variable or a function defined in the parent component to the child component. This convenience is enabled by Vue.js automatically assuming that any unrecognized attribute in a child component is a prop and passes it accordingly.

    Additionally, in Vue, the expression v-bind:msg="value" can be simplified to :msg="value". This shorthand notation improves code readability and reduces verbosity.

    Remember, while this shorthand is convenient, using the colon (:) explicitly can enhance code clarity, especially when working in a team or revisiting the code in the future.

    You can refer to dynamic vs static props: https://vuejs.org/guide/components/props.html#static-vs-dynamic-props