JackJack
JackJack

Reputation: 632

Can't display data from parent in child component

I'm new to Vue.js and trying to build a small application that a user can select a number and view it in another page. The data passed from the parent component was not displayed in the child component like "You select: (a number)", it showed "You select:", without the number passed from the parent. Where did I do wrong? I really can't figure it out.

ParentComponent.vue

    <template>
        <div>
            <p>Select a number: 
            <select v-model="num">
                <option disabled value="">Select</option>
                <option v-for="n in 10">{{n}}</option>
                <child-component v-bind:select="num"></child-component>
            </select>
            </p>
        </div>
    </template>

    <script>
    import ChildComponent from '../components/ChildComponent'
    export default {
      name: 'ParentComponent',
      components: {
        "child-component": ChildComponent
      },
      data () {
        return {
          num: 0,
        }
      }
    }
    </script>

    <style scoped>
    </style>

ChildComponent.vue

<template>
  <div>
    <h2>{{msg}}</h2>
    <p>You select: {{select}}</p>
  </div>
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    select: Number
  },
  data () {
    return {
      msg: 'ChildComponent'
    }
  }
}
</script>

<style scoped>

</style>

Upvotes: 1

Views: 176

Answers (1)

Hozhabr
Hozhabr

Reputation: 452

You can't use <child-component> in the <select></select> tags, please pull out it from the select tag and run it.

<template>
    <div>
        <p>Select a number: 
        <select v-model="num">
            <option disabled value="">Select</option>
            <option v-for="n in 10">{{n}}</option>
        </select>
        <child-component v-bind:select="num"></child-component> /// run it in here//
        </p>
    </div>
</template>

<script>
import ChildComponent from '../components/ChildComponent'
export default {
  name: 'ParentComponent',
  components: {
    "child-component": ChildComponent
  },
  data () {
    return {
      num: 0,
    }
  }
}
</script>

<style scoped>
</style>

Upvotes: 1

Related Questions