Vue 3 Composition api 将数据对象传递给 child

Vue 3 Composition api pass data boject to child

我想将反应数据 object 传递给 child,但应用程序显示空白页面,没有任何错误消息。我想使用合成 api.

Parent:

<template>
  <Landscape :viewData="viewData"/>
</template>

<script>
  import { onMounted, onUnmounted, ref, inject } from 'vue';

  export default {
  name: 'App',
  setup() {
    const resizeView = ref(false)
    const mobileView = ref(false)
    const viewData = reactive({resizeView, mobileView})
    viewData.resizeView.value = false
    viewData.mobileView.value = false
    // lets do sth to change viewData

    return {
      viewData
    }
  },
  components: {
      Landscape
    }
  }
</script>

Child:

<template>resize- {{viewData.resizeView}} mob {{viewData.mobileView}}
</template>

<script>

export default {
  name: 'Header',
  props: {
    viewData: Object,
  },
  setup() {
    return {
    }
  }
}
</script>

一切正常,当在 parent 中时,数据 object 像这样直接传递

<Landscape :viewData="{resizeView: false, mobileView: false}"/>

根据关于 reactive 个对象的 Vue 文档:

The reactive conversion is "deep"—it affects all nested properties.

因此您不需要将每个变量包装为 reactive 对象中的 ref(除非您想解包 ref 变量)。检查 Vue docs 以获取有关 Vue 中反应性 API 的更多信息。

我在 Landscape 组件中提供了 refreactive 的一些基本用法。将此粘贴到您的 App.vue:

<template>
  <button @Click="changeResize" type="button">Change ref values</button>
  <Landscape :viewData="viewData" />

  <br />
  <br />

  <button @Click="changeReactiveSize" type="button">
    Change reactive values
  </button>
  <Landscape :viewData="otherViewData" />
</template>

<script>
  import { onMounted, onUnmounted, ref, inject } from 'vue';

  export default {
  name: 'App',
  setup() {
    const resizeView = ref(false);
    const mobileView = ref(false);
    const viewData = {
      resizeView,
      mobileView,
    };
    const changeResize = () => {
      viewData.resizeView.value = !viewData.resizeView.value;
      viewData.mobileView.value = !viewData.mobileView.value;
    };

    const otherViewData = reactive({
      mobileView: false,
      resizeView: false,
    });

    const changeReactiveSize = () => {
      otherViewData.resizeView = !otherViewData.resizeView;
      otherViewData.mobileView = !otherViewData.mobileView;
    };

    return {
      viewData,
      otherViewData,
      changeResize,
      changeReactiveSize,
    };
  },
  components: {
      Landscape
    }
  }

您还可以在 stackblitz 上查看此代码示例。