programing

Vue 3: 메서드 함수에서 상태에 액세스하는 방법

goodjava 2023. 1. 24. 08:12

Vue 3: 메서드 함수에서 상태에 액세스하는 방법

Vue에서는 처음이라 Vuex의 기본 부분이 누락되거나 구성 API가 작동하는 방식이 누락될 수 있습니다.저는 제 API에 POST 요청을 하려고 합니다.세션 저장소에 사용자 ID를 저장하지 않고 스토어에서 가져오고 싶습니다.상태 값의 계산된 검색을 비동기 API 메서드 호출에 전달할 수 없습니다.미정의로 로그에 기록됩니다.상태의 사용자는 로그인 또는 등록 후에 입력됩니다.지도 감사합니다!

컴포넌트의 컴포지션 API 스크립트태그

export default {
  name: 'ModalContent',
  setup() {
    const store = useStore();
    const uid = computed(() => store.state.user.data.id);
    const loading = ref(true);
  },
    data() {
    return {
      session_name: "",
      dated: "",
      time_est: 60,
    };
  },
  methods: {
    async newSession() {
      const { session_name, dated, time_est, uid } = this;
      console.log(uid) ***UNDEFINED***     
      // const res = await fetch(
      //   "https://www...",
      
    }

Vuex 스토어

const store = createStore({
    state: {
        status: '',
        user: {},
        token: sessionStorage.getItem('TOKEN'),
    },
    getters: {},
    actions: {
        storeUserData({commit}, data) {
            commit('setUser', data.user);
            commit('setToken', data.token)
            },
    },

당신의.setup함수는 객체를 반환하여 컴포넌트인스턴스에서 사용할 수 있는 모든 것을 표시해야 합니다.

setup() {
  const store = useStore();
  const uid = computed(() => store.state.user.data.id);
  const loading = ref(true);
  return { loading, uid }
},

지금이다this.loading그리고.this.uid어떤 방법으로든 동작하며 템플릿에서 둘 다 액세스할 수 있습니다(예:loading그리고.uid).


, 적절한 방법은 셋업 함수 내에서 메서드를 이동하는 것입니다(이 메서드를const)는, 다음의 행에 따릅니다.

setup() {
  const store = useStore();
  const uid = computed(() => store.state.user.data.id);
  const loading = ref(true);
  const newSession = async () => {
    return await //... call your API
  }        
  return { loading, uid, newSession }
},

템플릿에 필요한 경우 셋업에서 반환된 개체에 추가합니다.
그렇지 않으면 폭로할 필요가 없습니다.

이상적으로는 리팩터링을 마치면methods,computed,watch, 임의의 훅 (예:mounted,beforeDestroy)는 내부로 옮겨야 합니다.setup.

언급URL : https://stackoverflow.com/questions/71157516/vue-3-how-to-access-state-in-a-method-function