| ์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
- Vue.js
- kotlin algorithm
- ์ฝํ๋ฆฐ
- vue3
- python
- ์ฝํ๋ฆฐ ์คํ
- ๋ฐฐ๋น์ฃผ
- kotlin ์๊ณ ๋ฆฌ์ฆ
- Java
- ๋ฐฑ์ค
- ๋ฏธ๊ตญ์ฃผ์
- linux
- js
- ํ๋ก๊ทธ๋๋จธ์ค
- Swift
- java ์ฝ๋ฉ ํ ์คํธ
- ๋ฐฑ์ค ์ฝํ๋ฆฐ
- ์๋ฐ ์๊ณ ๋ฆฌ์ฆ
- ํ์ฝํ
- ์๊ณ ๋ฆฌ์ฆ
- GIT
- ์ฝํ๋ฆฐ ์๊ณ ๋ฆฌ์ฆ
- ๋ฏธ๊ตญ๋ฐฐ๋น์ฃผํฌ์
- ์๋ฐ์คํฌ๋ฆฝํธ
- ํ์ด์ฌ
- pnpm
- Kotlin
- javascript
- ์๋ฐ
- CI/CD
- Today
- Total
๐ ์ ์ด์ ๋จธ๋ฆฟ์์ผ๋ก
[Vue3] TypeError: Cannot read properties of undefined (reading '$store') ํด๊ฒฐ ๋ณธ๋ฌธ
[Vue3] TypeError: Cannot read properties of undefined (reading '$store') ํด๊ฒฐ
Space_Jin 2024. 1. 1. 22:00Vue3 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๋ฅผ ๋ถ๋ฌ์์ ์ฌ์ฉํ ์ ์์ต๋๋ค.