• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

현재 vue2 typescript 적용 된 프로젝트에서 composition api 적용 시 에러 문의

22.04.05 17:08 작성 조회수 543

1

현재 vue2 vue-news 프로젝트에서 "@vue/composition-api": "^1.4.9",를 활용하여 composition api 적용 중

dispatch(action)을 호출 하는경우

[vuex] unknown action type: FETCH_NEWS가 발생하고 있습니다.

import { defineComponent,reactive, toRefs } from '@vue/composition-api'
import { MutationTypes } from './store/mutations'
import { ActionTypes } from './store/actions'

export default defineComponent({
name: 'App',
async setup(props, context) {
const store = context.root.$store
console.log(store?.state)
store?.commit(MutationTypes.SET_NEWS, [1, 2, 3])
console.log(ActionTypes.FETCH_NEWS)
await store?.dispatch('FETCH_NEWS')
    await store?.dispatch(ActionTypes.FETCH_NEWS)

// 데이터 함수 선언(data)
const state = reactive({
loading: false,
})

return {
...toRefs(state),
}
},
})

 

소스 확인 결과 api 호출 시 store 객체를 접근하는 경우 위와 같은 에러가 발생하며,

store객체를 주석처리 하거나 ActionTypes를 분리하여 import를 하면 정상적으로 api 호출이 되었습니다. 

import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
// import { setDefaultOptions } from '@/api/instance/intercepter'
import store from '@/store'

const APP_BASE_URI: string =
""
const options = {}

function create(url: string, options = {}): AxiosInstance {
const instance = axios.create(Object.assign({ baseURL: url }, options))
console.log(store)
instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
return config
},
(error) => {
return Promise.reject(error.response)
},
)
return instance
}

 

import { fetchNews } from '@/api'
import { ActionContext } from 'vuex'
import { Mutations, MutationTypes } from './mutations'
import { RootState } from './state'

enum ActionTypes {
FETCH_NEWS = 'FETCH_NEWS',
}

type MyActionContext = {
commit<K extends keyof Mutations>(
key: K,
payload: Parameters<Mutations[K]>[1],
): ReturnType<Mutations[K]>
} & Omit<ActionContext<RootState, RootState>, 'commit'>

const actions = {
async [ActionTypes.FETCH_NEWS](context: MyActionContext, payload?: any) {
const { data } = await fetchNews()
context.commit(MutationTypes.SET_NEWS, data)
return data
},
}

type Actions = typeof actions

export { actions, Actions, ActionTypes }

 

혼자 해결 방법을 찾아보다가 방법이 없어 문의 드립니다..

해당 에러가 발생하는 이유가 뭔지 궁금합니다..

 

 

답변 1

답변을 작성해보세요.

1

안녕하세요, context.root로 접근하는 대신 아래와 같이 해보시겠어요? :)

import store from '@/store/index';

 

setup() {

  store.dispatch('FETCH_NEWS');

}