首页 > 解决方案 > Vue JS:在组件的组件内传递道具

问题描述

我有这个简单的脚本,里面有来自其他组件的道具,当我安慰它时它工作正常。但是我怎样才能在我的line-chart组件下传递道具呢?

export default {
    props: ['dataset'],
    components:{
    'line-chart': {
          extends: Bar,
          beforeMount () {
            try{
              this.addPlugin(horizonalLinePlugin)
              //console.log(this.$props);
              console.log($this.$props.dataset); <- How can show it here?

            }catch(err){
            }
          },
          mounted () {
            this.renderChart(chartOption, chartSettings
            )
          }
        }
    },
    created(){
      console.log(this.$props) <- Working fine
    },
    mounted(){

    }
  }

标签: javascriptvue.js

解决方案


您不能props直接从子组件访问父组件;您需要在子组件中声明 prop,然后从父组件向其传递数据。

export default {
  props: ['dataset'],
  components:{
    'line-chart': {
      extends: Bar,
      props: ['dataset'],                // declare the prop
      beforeMount () {
        try {
          this.addPlugin(horizonalLinePlugin)
          console.log(this.dataset);     // access with this.dataset
        } catch(err) {
        }
      },
      mounted () {
        this.renderChart(chartOption, chartSettings)
      }
    }
  }

然后在您的模板中,将dataset父组件传递给子组件:

<line-chart :dataset="dataset"></line-chart>

推荐阅读