Search code examples
vue.jspropertiescomponents

Passing props values to component


I have this component: InputField.vue

<template>
  <div class="w-full">
    <label class="sr-only" :for="name"></label>
    <input
      :placeholder="label"
      :name="name"
      class="border-b border-black w-full appearance-none w-full py-4 px-3 text-grey-darker leading-tight"
    />
  </div>
</template>
<script>
export default {
  props: {
    label: {
      type: String,
      required: true,
      default: 'label', /* <--------- Always prints default */
    },
    name: {
      type: String,
      required: true,
      default: 'name', /* <--------- Always prints default */
    },
  },
  data() {
    return {}
  },
}
</script>

And this is how i'm using it from another component:

<inputField :label="Hola" :name="nombre" />

But label and name are allways the default values defined in the component declaration,

Any idea what i'm missing?


Solution

  • I'm going to capitalize on the snippet done by Utlime but there a lot of problems in that answer, in fact you must NOT take out the ":" as it is the thing that binds it as props and actually will let multiple instances of the component to have their "own" props states, just call it like :aProp="'something'" if you are using hard coded values, if you're passing a variable then go with :aProp='variable' The correct example would be:

    Vue.component('InputField', {
      template: `
        <div class="w-full">
        <label class="sr-only" :for="name"></label>
        <input
          :placeholder="label"
          :name="name"
          class="border-b border-black w-full appearance-none w-full py-4 px-3 text-grey-darker leading-tight"
        />
      </div>
      `,
    
      props: {
        label: {
          type: String,
          required: true,
          default: 'label', /* <--------- No longer prints default if props are given */
        },
        name: {
          type: String,
          required: true,
          default: 'name',
        },
      },
    });
    
    new Vue({
      el: '#app',
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <input-field :label="'Hola'" :name="'nombre'"></input-field>
      <input-field :label="'Que tal Toni'" :name="'toni'"></input-field>
    </div>