Home > Blockchain >  Vue.js Cannot read properties of undefined (reading 'router') error
Vue.js Cannot read properties of undefined (reading 'router') error

Time:11-23

I'm new to Vue.js and I have created one simple form for the user and storing data using API.

On submit I'm calling this function:

setup(props, { emit }) {
    const blankData = {
      customer: '',
      template: '',
      rate: '',
      property_from: '',
      property_to: '',
      move_date: '',
      num_days: '',
      token: '',
      details: '',
      customer_options: [],
      template_options: [],
      rate_options: [],
      property_from_options: [],
      property_to_options: [],
    }

    const userData = ref(JSON.parse(JSON.stringify(blankData)))
    const resetuserData = () => {
      userData.value = JSON.parse(JSON.stringify(blankData))
    }
    const toast = useToast()

    const onSubmit = () => {
      store.dispatch('app-user/addUser', userData.value)
        .then(
          response => {
            if (response.status === 1) {
              this.$router.push({ name: 'edit-user', params: { id: 10 } })
            }

            toast({
              component: ToastificationContent,
              props: {
                title: response.message,
                icon: response.toastIcon,
                variant: response.toastVariant,
              },
            })
          },
          error => {
            console.log(error)
          },
        )
    }

    const {
      refFormObserver,
      getValidationState,
      resetForm,
    } = formValidation(resetuserData)

    return {
      userData,
      onSubmit,
      refFormObserver,
      getValidationState,
      resetForm,
    }
  },

And trying to redirect the user to the edit page after user creation but I'm getting this error and not redirecting:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'router')

I have tried with this stackoverflow answer but getting same error:

const onSubmit = () => {
    const self = this
    store.dispatch('app-user/addUser', userData.value)
    .then(
        response => {
            if (response.status === 1) {
                self.$router.push({ name: 'edit-user', params: { id: 10 } })
            }
        },
        error => {
            console.log(error)
        },
    )
}

Any idea what I'm doing wrong in my code?

CodePudding user response:

You're using Vue 3 and a setup function; there is no this in a setup function.

See Accessing the Router and current Route inside setup.

Untested, but probably something like this will work:

setup() {
  const router = useRouter()

  const onSubmit = () => {
    // ... code omitted ...

    router.push({ name: 'edit-user', params: { id: 10 } })
  }

  return {
    onSetup,
    // other stuff...
  }
}

CodePudding user response:

I think this might be help

router with composition api https://next.router.vuejs.org/guide/advanced/composition-api.html

  • Related