【问题标题】:Vue props undefinedVue 道具未定义
【发布时间】:2018-04-10 08:15:59
【问题描述】:

我是 Vue 的新手,我正在尝试使用子组件的 props 获取父组件的数据,但是在执行 console.log() 时出现未定义的错误。

家长:

import axios from 'axios'
import PieChart from './components/PieChart'

export default {
  data () {
    return {
      requires: [],
      tested: [],
      requires_php: [],
      errors: [],
      url: 'https://api.miruc.co/plugins.min.json'
    }
  },
  created: function () {
    axios.get(this.url)
    .then(response => {
      this.requires = response.data[0]
      this.tested = response.data[1]
      this.requires_php = response.data[2]
    })
    .catch(e => {
      this.errors.push(e)
    })
  },
  components: {
    'pie-chart': PieChart
  }
}

孩子:

export default {
  extends: Pie,
  props: ['req'],
  mounted: function () {
    console.log(this.req)
    /*  */
  }
}

谁能告诉我我做错了什么?

【问题讨论】:

  • 我猜 http get 在到达你的 console.log 时仍在运行。
  • @RichardMatsen 我尝试使用setTimeout(function () { alert(this.req) }, 10000),但仍然遇到同样的错误。甚至 Chrome 上的 Vue 扩展都说它是未定义的。
  • 您可以通过在.then(response => { 方法中添加另一个console.log 并查看它们出现的顺序来确定。
  • 我在那里没有定义...这很奇怪,Vue 扩展说它存储了一个对象。
  • 好吧,我没想到会这样。 “Vue 扩展”——那是什么?

标签: vue.js vuejs2


【解决方案1】:

您需要将 props 传递给父模板中的子组件,例如:

<template>
//...
    <pie-chart :req="requires"></pie-chart>
//...
</template>

【讨论】:

    【解决方案2】:

    我不知道您对模板代码做了什么。但是看看当你像这样更改父母的代码时会发生什么:

    import axios from 'axios'
    import PieChart from './components/PieChart'
    
    export default {
      data () {
        return {
          requires: [],
          tested: [],
          requires_php: [],
          errors: [],
          url: 'https://api.miruc.co/plugins.min.json'
        }
      },
      created: function () {
        axios.get(this.url)
        .then(response => {
          Vue.set(this, 'requires', response.data[0])
          Vue.set(this, 'tested', response.data[1])
          Vue.set(this, 'requires_php', response.data[2])
        })
        .catch(e => {
          this.errors.push(e)
        })
      },
      components: {
        'pie-chart': PieChart
      }
    }
    

    要记住的一件事:每当您设置数组或对象元素时,请始终使用Vue.set。它确保了内部元素的反应性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-17
      • 2018-01-27
      • 2021-02-12
      • 2020-08-03
      • 1970-01-01
      • 2021-09-11
      • 2020-04-13
      相关资源
      最近更新 更多