【问题标题】:How to get access to the Root inside the setup method of Vue 3 component?如何在 Vue 3 组件的 setup 方法中访问 Root?
【发布时间】:2020-12-05 02:24:30
【问题描述】:

我有一个 Vue 应用程序。 我使用 vuex。 我这样创建了我的应用程序:

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

axios.defaults.baseURL = "https://localhost:44349";

const app = createApp(App)
  .use(router)
  .use(store)
  .mount("#app");

我的组件之一是我试图在 setup() 方法中访问 c​​ontext.root.$store ,但 context.root 未定义。

<script>
import {ref, computed } from "vue";

export default {
  name: "ClientList",

  setup(props, context) {
    
    const clients = ref([]);

    console.log(context);

    const clientOrdersLenght = computed(() => {
      return clients.value.length;
    });


    return { clients, clientOrdersLenght }
  },
  
};
</script>

我的想法是通过 context.root 访问我的商店。我用这个观看了视频和示例。但他们使用 'vue/composition-api' 作为导入来引用 Vue 2。

我错过了什么?

【问题讨论】:

    标签: vue.js vue-composition-api


    【解决方案1】:

    您也许可以直接包含和访问商店

    store.dispatch('myModule/myModuleAction') store.myModule.state.blabla

    import {ref, computed } from "vue";
    import store from './store/index'; // include store
    
    export default {
      name: "ClientList",
    
      setup(props) {
        
        const clients = ref([]);
    
        const clientOrdersLength = computed(() => {
          store.dispatch('myAction'); // call dispatch
          store.state.myItem // or access store's state
          return clients.value.length;
        });
    
        return { clients, clientOrdersLength }
      },
      
    };
    

    【讨论】:

      【解决方案2】:

      我找到了一种使用 vuex 中的 getStore() 访问我的商店的简单方法。这很酷。 但由于该功能的其他原因,我或其他人将需要访问应用程序的 $root(vue 实例)。那么现在可能正确的问题是如何在子组件中获取应用程序的 $root(vue 实例)?

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 2021-01-10
        • 2021-10-20
        • 2019-09-10
        • 1970-01-01
        • 2021-11-11
        • 2022-12-09
        • 2017-06-05
        • 2019-11-05
        相关资源
        最近更新 更多