sourcecode

vuex 스토어의 악리를 통해 게시한 후 리다이렉트하는 올바른 방법

copyscript 2022. 8. 17. 23:53
반응형

vuex 스토어의 악리를 통해 게시한 후 리다이렉트하는 올바른 방법

nuxtjs, axios 및 vuex를 사용하여 폼 컴포넌트에서 투고하고 데이터를 백엔드에 투고하고 있습니다.

게시된 경우 레코드 보기 화면으로 리디렉션하고 ID를 사용하여 반환된 정보로 내용을 채웁니다.

따라서 경로는 /cases/contrace25일 수 있습니다(14325가 생성 후 반환되는 ID인 경우)

어떻게 하면 좋을까요?

내 vuex 스토어에 다음 코드가 있습니다.

export const state = () => ({
    cases: []
  })

  // ***  MUTATIONS  ***
  export const mutations = {
    add(state, newCase ) {
    state.cases.push(newCase)
  },

  }

  // ***  ACTIONS  ***
  export const actions = {
    addCase(context, newCase) {
    const createdCase = {
        ...newCase
    }
    axios.post("http", createdCase)
    .then(result => {
        context.commit('add', {...createdCase, id: result.data.name})
    })
    .catch(e => console.log(e));
    },
  }

내 컴포넌트에는 다음과 같은 것이 있습니다.

    import { mapMutations, mapGetters, mapActions } from 'vuex'
export default {

  data () {
    return {
      newCase: {
        caseName: '',
        summary: '',
        status: 'live',
      },
    }
  },

  methods: {

     ...mapActions([
      'addCase' 
    ]),
    onSubmit() {
      // Save the post
      this.$store.dispatch('addCase').then(path => {
        this.$router.redirect(path)
      }).catch((err) => {
        console.log(err)
      })  
    },
  }
}
</script>

스토어에서 새 ID를 반환하고 cases/1을 '/cases/' + 새 ID로 바꾸려면 어떻게 해야 합니까?

늘 신세 많이 졌습니다.

이러한 방법으로 작업을 개선하면 충분합니다.

addCase(context, newCase) {
  return new Promise ((resolve, reject) => {
    const createdCase = {...newCase}
    axios.post('http', createdCase).then(result => {
      context.commit('add', {...createdCase, id: result.data.name})
      resolve(/*path*/)
    }).catch(e => {
      console.log(e)
      reject(/*reason*/)
    })
  })
}

그런 다음 이렇게 사용합니다.

this.$store.dispatch('addCase', context).then(path => {
  this.$router.redirect(path)
})

언급URL : https://stackoverflow.com/questions/50951148/correct-way-to-do-a-redirect-after-posting-through-axios-in-a-vuex-store

반응형