簡體   English   中英

使用 Vue 3 Composition 創建全局商店 API

[英]Create a Global Store using Vue 3 Composition API

我正在嘗試僅使用 Vue 3 Composition API 創建一個全球商店。

直到現在我一直在做實驗,我讀了很多如何使用 Composition API,但我不知道如何使用provideinject

我所知道的是provide將擁有將傳遞給子組件的所有數據,所以我認為我應該將商店導入main.ts 代碼如下所示:

這是商店(src/store/index.ts):

import { reactive, readonly } from "vue";

const state = reactive({
  fnacResults: [],
  interResults: [],
});

export default { state: readonly(state) };

這是main.ts

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store/index";

createApp({ provide: { store }, }, App)
  .use(router)
  .mount("#app");

當父組件有數據時,如果我使用inject ,我將能夠訪問商店內的所有數據。 但就我而言,它不起作用。 當我在main.ts文件中設置provide時,我感覺錯誤開始了。

您是否嘗試過使用 Composition API 和provideinject創建一個全球商店?

順便說一句,我的組件文件( src/views/Home.vue )看起來像這樣:

<template>
  <div>{{ store.state.fnacResults }}</div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  inject: ['store']
});
</script>

申請 API

createApp的第一個參數應該是組件定義(在您的情況下是App )。 相反,您可以使用應用程序實例的provide()

createApp(App).provide('store', store).mount('#app')

演示

作文 API

對於組合 API,您可以像這樣使用 provide

// Parent.vue
import { provide } from 'vue'
import store from '@/store'

export default {
  setup() {
    provide('store', store)
    //...
  }
}

然后在一些后代組件中,你會注入它:

// Child.vue
import { inject } from 'vue'

export default {
  setup() {
    const store = inject('store')

    return {
      results: store.state.interResults
    }
  }
}

進口

或者,只在需要的地方導入商店並直接使用它可能更簡單:

// Child.vue
import store from '@/store'

export default {
  setup() {
    return {
      results: store.state.interResults
    }
  }
}

嘗試在根組件App中提供store ,然后在任何子組件中使用它:

export default {
   name:"App",
  provide: { store },

...

你好組件:

<template>
  <div>
    <ul>
      <li v-for="(item, i) in fnacResults" :key="i">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  inject: ["store"],
  computed: {
    fnacResults() {
      return this.store.state.fnacResults;
    },
  },
  mounted() {
    console.log(this.store.state);
  },
};
</script>

<style>
</style>

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM