如何在Vue 3组件的设置方法中访问Root?

时间:2020-08-15 11:40:26

标签: vue.js vue-composition-api

我有一个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()方法中的context.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。

我想念什么?

2 个答案:

答案 0 :(得分:0)

您也许可以直接加入并访问商店

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 }
  },
  
};

答案 1 :(得分:0)

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