【问题标题】:Vue 3 Composition api pass data boject to childVue 3 Composition api将数据对象传递给孩子
【发布时间】:2022-01-26 00:58:46
【问题描述】:

我想将响应式数据对象传递给子级,但应用程序显示空白页面而没有任何错误消息。我想使用合成 api。

家长:

<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>

孩子:

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

<script>

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

一切正常,当在父级时,数据对象像这样直接传递

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

【问题讨论】:

  • const viewData = reactive({resizeView: false, mobileView: true}) 您可以删除两个 ref 并使用单个反应变量。还有其他选择。
  • 直接改viewData.resizeView = true;,是反应式的。
  • 传递可写对象作为道具不是一个好习惯。 viewData.resizeView.value - 它不是 ref,refs 被解包在响应对象中,否则保留它没有多大意义 reactive

标签: javascript vue.js vue-component vuejs3 vue-composition-api


【解决方案1】:

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

响应式转换是“深度”的——它会影响所有嵌套属性。

因此,您不需要将每个变量包装为 ref 对象中的 reactive (除非您想解开 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 上查看此代码示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2021-03-19
    • 2022-11-25
    • 2021-12-31
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多