programing

Vue.js Vuex 스토어를 올바르게 사용하는 방법watch() 메서드가 맞습니까?

prostudy 2022. 6. 7. 21:28
반응형

Vue.js Vuex 스토어를 올바르게 사용하는 방법watch() 메서드가 맞습니까?

가게에 대해 읽었어요.watch()는 유효한 예를 찾을 수 없었습니다.

Vuex 워치(fn: 함수, 콜백:기능, 옵션:오브젝트):함수 fn의 반환값을 반응적으로 감시하고 값이 변경되면 콜백을 호출합니다.fn은 스토어의 상태를 첫 번째 인수로 받고 getters는 두 번째 인수로 받습니다.Vue의 VM과 동일한 옵션을 사용하는 선택적 옵션 개체를 허용합니다.$watch 메서드시청을 중지하려면 반환된 패치 해제 함수를 호출합니다.

Firebase로 로그인하기 위한 Vuex 액션이 있다.

signUserIn ({commit}, payload) {
  commit(types.SET_LOADING, true)
  commit(types.CLEAR_ERROR)
  firebase.auth().signInWithEmailAndPassword(payload.email, payload.password)
  .then((user) => {
    commit(types.SET_LOADING, false)
    const newUser = { id: user.uid, name: user.displayName, email: user.email, photoUrl: user.photoURL }
    commit(types.SET_USER, newUser)
  })
  .catch((error) => {
    commit(types.SET_LOADING, false)
    commit(types.SET_ERROR, error)
  })
},

Signin vue 컴포넌트에서 이 액션을 디스패치합니다.

제 비즈니스 케이스에서는 사용자가 아직 등록되어 있지 않기 때문에 로그인이 실패하기 때문에 스토어에서 erro가 발생하고 커밋되지만, 제 컴포넌트에서는 디스패치 직후 에러가 발생하지 않기 때문에 스토어에서 로딩값을 true/false로 설정하고 변경 상황을 지켜봐야 합니다.그래서 매장을 이용하려고 해요.워치()

onSignIn 메서드(검증 후)

    this.$store.dispatch('signUserIn', { email: this.email, password: this.password })
      console.log('loading...: ', this.$store.getters.loading)
      this.$store.watch(this.$store.getters.loading, () => {
        console.log('loaded')
        console.log('onSIgnin error', this.error.code)
      })

Vuex 에러가 표시된다.

 Error: [vuex] store.watch only accepts a function 

제가 어떤 기능을 통과하고 있는 거죠?

피드백 감사합니다.

watch의 첫 번째 인수는 상태를 첫 번째 인수로 받고 getters를 두 번째 인수로 받는 함수입니다.따라서 이와 같이 getters에 접속하면 반환값이 감시 대상입니다.

      this.$store.watch((state, getters) => getters.loading, () => {
        console.log('loaded')
        console.log('onSIgnin error', this.error.code)
      })

언급URL : https://stackoverflow.com/questions/50932315/vue-js-vuex-how-to-use-correctly-the-store-watch-method-correctly

반응형