0

I created a new VueJS 3 project with Typescript. Further I added Vuex 4 as my store. But I can't figure out what I am doing wrong to import the store into my Vue Component.

Currently I get an error in my browser's console: Uncaught (in promise) TypeError: Cannot read property 'parentNode' of null

How must I import my store to use it in my component?

// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { store, key } from "./store/store";

createApp(App)
    .use(store, key)
    .mount('#app')

// store.ts
import {InjectionKey} from "vue"
import {createStore, useStore as baseUseStore, Store} from "vuex"

export interface State {
    ...
}

export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
    state: {
        someArray: [{...}]
    },
    mutations: {},
    getters: {
        getObjects: (state) => state.someArray
    }
})

export function useStore() {
    return baseUseStore(key)
}

// Component
<template>...</template>

<script lang="ts">
import {defineComponent} from "vue";
import {useStore} from "../store/store";

export default defineComponent({
  name: 'Comp',
  data() {
    return {
      store: null,
    }
  },
  computed: {
    something() {
      return this.store.getters.getObjects
    }
  },
  setup() {
    const store = useStore()
    return store
  }
}

1 Answer 1

1

The problem is you're mixing the Composition API with the Options API. You've declared your own store data property, and then in setup(), you're re-declaring store by returning it.

To resolve the issue, just remove the data and computed options, and stick with the Composition API (just use setup):

<template>
  <div>{{ something }}</div>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue'
import { useStore } from '../store/store'

export default defineComponent({
  setup() {
    const store = useStore()
    return {
      something: computed(() => store.getters.getObjects)
    }
  }
})
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.