Vue-如何将父母裁判传递给孩子作为道具?

时间:2018-08-03 08:43:32

标签: javascript vue.js vuejs2

我正在尝试将当前组件的ref传递给子组件,如下所示:

<template>
    <div class="screen" ref="screen">
        <child-component :screenRef="screenRef">
        </child-component>
    </div>
</template>


<script>
    const Parent = {
        name: 'parent',
        data: {
            screenRef: {}
        },
        mounted() {
            this.screenRef = this.$refs['screen']
        }
    }
</script>

由于Vue.js类型不支持HTMLDivElement,因此在将screenRef定义为prop时,我在子组件中遇到了错误。

const ChildComponent = {
  name: 'child',
  props: {
    screen: {
      type: HTMLDivElement,
      default: {}
    }
  }
}

有人可以告诉正确的方法吗?

4 个答案:

答案 0 :(得分:1)

只需尝试通过以下方式从子组件访问父对象:

this.$parent

this.$el.parent

或在子组件中使用 inheritAttrs 选项,将属性从父级不透明地传递给子级:

const ChildComponent = {
  inheritAttrs: true,
  name: 'child',
  props: {
    screen: {
      type: HTMLDivElement,
      default: {}
    }
  }
}

答案 1 :(得分:0)

如果您需要来自其他组件的数据,只需将其与道具一起传递即可。

或者,如果您需要多个组件中的数据,请尝试使用Vuex:

https://vuex.vuejs.org/guide/

答案 2 :(得分:0)

您所做的所有事情都是正确的。只是不要声明type道具所需的screen。以下props: {screen: {default: {}}}可以解决问题。

请注意,mounted钩子是将$refs元素分配给$data项的正确位置,因为前者未在created钩子中定义。 / p>

答案 3 :(得分:0)

您也可以将default更改为null并删除类型。就我而言,我必须通过兄弟姐妹的裁判。

const ChildComponent = {
  name: 'child',
  props: {
    screen: {
      default: null
    }
  }
}
相关问题