【问题标题】:Vue.js Cannot read properties of undefined (reading 'router') errorVue.js 无法读取未定义的属性(读取“路由器”)错误
【发布时间】:2021-12-31 19:25:16
【问题描述】:

我是 Vue.js 的新手,我为用户创建了一个简单的表单并使用 API 存储数据。

在提交时我正在调用这个函数:

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,
    }
  },

并尝试在创建用户后将用户重定向到编辑页面,但我收到此错误并且没有重定向:

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

我已经尝试过这个stackoverflow answer,但得到了同样的错误:

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)
        },
    )
}

知道我在代码中做错了什么吗?

【问题讨论】:

  • this 在这种情况下指的是什么?您的 onSubmit 函数在哪里定义,它在哪里使用?需要更多上下文。

标签: vue.js vue-router vuejs3


【解决方案1】:

您正在使用 Vue 3 和设置功能;设置函数中没有this

Accessing the Router and current Route inside setup

未经测试,但可能这样的事情会起作用:

setup() {
  const router = useRouter()

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

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

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

【讨论】:

    【解决方案2】:

    我认为这可能会有所帮助

    带有组合 API 的路由器 https://next.router.vuejs.org/guide/advanced/composition-api.html

    【讨论】:

    • 是的。我正在使用 Vuexy - Vuejs 主题。
    • 你更新问题后我更新了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2020-05-22
    • 2019-08-13
    • 1970-01-01
    • 2017-11-20
    • 2022-07-06
    • 2021-12-31
    相关资源
    最近更新 更多