无法在子组件中显示来自父项的数据

时间:2018-09-21 21:49:56

标签: vuejs2 vue-component

我是Vue.js的新手,它试图构建一个小的应用程序,用户可以选择一个数字并在另一个页面中查看它。从父组件传递的数据未在子组件中显示,例如“您选择:(一个数字)”,而是显示“您选择:”,而没有从父组件传递的数字。我在哪里做错了?我真的不知道。

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>

1 个答案:

答案 0 :(得分:1)

您不能在<child-component>标记中使用<select></select>,请从select标记中将其拔出并运行它。

<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>