๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Programming/Vue

[Vue3] TypeError: Cannot read properties of undefined (reading '$store') ํ•ด๊ฒฐ

728x90
๋ฐ˜์‘ํ˜•

Vue3 TypeError: Cannot read properties of undefined (reading '$store') ํ•ด๊ฒฐํ•˜๊ธฐ

Vuex์˜ store ์‚ฌ์šฉํ•  ๋•Œ ์ž์ฃผ ๋ณผ ์ˆ˜ ์žˆ๋Š” ์˜ค๋ฅ˜ ์ž…๋‹ˆ๋‹ค.

 

vue2์™€ vue3์˜ store์˜ ์‚ฌ์šฉ๋ฒ•์ด ๋‹ฌ๋ผ์„œ ์ผ์–ด๋‚  ์ˆ˜ ์žˆ๋Š” ์˜ค๋ฅ˜ ์ž…๋‹ˆ๋‹ค.

1. main.js ํ™•์ธ

vue2์—์„œ vue3๋ฅผ ์˜ค๋ฉด์„œ main.js์— store๋ฅผ ์‚ฌ์šฉํ•˜๊ณ ํ•˜๋Š” ๋ช…์‹œ๋ฒ•์ด ๋ฐ”๋€Œ์—ˆ๊ธฐ์— ๋งŽ์ด ๋‚˜๋Š” ์˜ค๋ฅ˜ ์ž…๋‹ˆ๋‹ค.

 

ํ•ด๊ฒฐ๋ฒ•

import { createApp } from 'vue'
import App from './App.vue'
import { store } from './store/store'

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

main.js

store.js๋ฅผ importํ•œ ํ›„ use(store) ์ถ”๊ฐ€ํ•ด ์ฃผ์–ด์•ผ App ์ „์—ญ์—์„œ store์— ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

2. script ์— useStore ์‚ฌ์šฉ

ํŠน์ • component์—์„œ๋Š” ์ž˜ ์‚ฌ์šฉ์ด ๋˜์—ˆ๋Š”๋ฐ ํŠน์ • component์—์„œ๋Š” ์œ„ ๊ฐ™์€ ์˜ค๋ฅ˜๊ฐ€ ๋‚œ๋‹ค๋ฉด script๋ฅผ ํ™•์ธ ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

import { createStore } from "vuex";

export const store = createStore({
   state: {
    items: ['item1', 'item2']
   },
   mutations: {
    consoleItem() {
        console.log('addOneItem')
    }
   }
});

main.js ์˜ˆ์‹œ

<template>
	<li v-for="item in $store.state.items" v-bind:key="item">
    	{{ item }}
	</li>
</template>

component ์˜ˆ์‹œ

<template> ํƒœ๊ทธ ์•ˆ์—์„œ๋Š” $store.state.items ์ฒ˜๋Ÿผ $store ํ‚ค์›Œ๋“œ์— ๋ฐ”๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

<script> ํƒœ๊ทธ ์•ˆ์—์„œ ์œ„์ฒ˜๋Ÿผ $store ํ˜น์€ this.$store ์ฒ˜๋Ÿผ $store ํ‚ค์›Œ๋“œ๋ฅผ ํ†ตํ•ด์„œ ์ ‘๊ทผํ–ˆ๋‹ค๋ฉด, undefined ์˜ค๋ฅ˜๊ฐ€ ๋‚  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ด ๊ฒฝ์šฐ, useStore API๋ฅผ ํ†ตํ•ด์„œ store ์ƒ์„ฑํ•ด์„œ ์‚ฌ์šฉํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.

 

<template>
	<li v-for="item in $store.state.items" v-bind:key="item" @click='callStore'>
    	{{ item }}
	</li>
</template>

<script setup>
    import { useStore } from 'vuex';

    const store = useStore();	//store ์ •์˜

    const callStore = () => {
        store.commit('consoleItem');	//store.js์˜ mutations์˜ consoleItem ํ˜ธ์ถœ
    }
</script>

script์—์„œ store ์‚ฌ์šฉํ•œ component ์˜ˆ์‹œ

์œ„ ์ฒ˜๋Ÿผ vuex์—์„œ ์ œ๊ณตํ•˜๋Š” useStore๋ฅผ ์‚ฌ์šฉํ•ด store๋ฅผ ๋ถˆ๋Ÿฌ์™€์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•