【问题标题】:Can't display data from parent in child component无法在子组件中显示来自父级的数据
【发布时间】:2018-09-21 21:49:56
【问题描述】:

我是 Vue.js 的新手,正在尝试构建一个小型应用程序,用户可以选择一个数字并在另一个页面中查看它。从父组件传过来的数据,在子组件中没有像“你选择:(一个数字)”这样显示,而是显示“你选择:”,没有从父组件传过来的数字。我哪里做错了?实在想不通。

父组件.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>

【问题讨论】:

  • Vue js 有所谓的computed 道具,它应该可以帮助你
  • 我想知道为什么代码不起作用
  • 这是因为 vue js Vue props 和 state 的“缓存”是惰性的,所以如果你想计算你的属性来更新你的组件,你应该使用计算的 porps
  • 如果我将“props”更改为“computed”,它会显示 NaN。我应该为计算的道具添加什么功能?
  • 添加诸如getMsg: function(){return this.msg}之类的东西并在您看来使用&lt;child-component v-bind:select="getMsg"&gt;&lt;/child-component&gt;

标签: vuejs2 vue-component


【解决方案1】:

&lt;child-component&gt;不能在&lt;select&gt;&lt;/select&gt;标签中使用,请从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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2021-07-13
    • 1970-01-01
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多