在 vue 组件的下拉列表中使用来自一个组件的数据

Using data from one component in dropdown list in vue component

我有两个 vue 页面(使用 quasar)。我想将一页中的数组用作另一页中的下拉列表。我认为它是作为道具传递的,但我无法弄清楚结构。它看起来不像是真正的子-父结构。该数组作为计算函数进行计算。

如何在计算函数 optionsArray 中使用第 2 页中计算的数组作为第 1 页中的“选项”?

Vue 第 1 页

<template>
 <form >
  <q-select
    :options="options"
  />
  <q-btn label="Save" type="submit"  />
 </form>
</template>
<script>
  export default {
    name: "AddEntry",
    props: ["options"],
</script>

Vue 第 2 页

</template>
<script>
  export default {
    name: "ListEntries",
    setup(){

      //computed properties

      const optionsArray = computed(
       () => (s) =>
           optionsArray.value.filter(stage || !stage
              )
    }
 }
</script>
  

您必须使用 props 传递数据,共享整个代码和控制台错误(如果存在)

Provide/Inject 就是您要找的。

在你的 Page2.vue 中,使用 provide 方法:

<script>
import { provide, computed } from "vue";
  export default {
    name: "ListEntries",
    setup(){

      //computed properties

      const optionsArray = computed(
       () => (s) =>
           optionsArray.value.filter(stage || !stage
              )

      // this will make optionsArray globally available
      provide('optionsFromPage2', optionsArray);
    }
 }
</script>

在你的 Page1.vue 中,使用 inject 方法:

<template>
 <form >
  <q-select
    :options="optionsArray"
  />
  <q-btn label="Save" type="submit"  />
 </form>
</template>
<script>
  import { inject } from "vue";
  export default {
    name: "AddEntry",
    props: ["options"],
    setup() {
        // access the options array with inject method
        const optionsArray = inject('optionsFromPage2')
        return {optionsArray};
     }
    
</script>