VUE2.7.14

109 阅读1分钟

vue2.7.14router/store相关问题

问题

1、this.$router is not defined

2、useRouter is not a function

解决

// utils
import { getCurrentInstance } from 'vue'

// 访问vuex
export const useStore = () => {
  const vm = getCurrentInstance()
  if (!vm) throw new Error('must be called in setup')
  return vm.proxy.$store
}
// 访问router
export const useRouter = () => {
  const vm = getCurrentInstance()
  if (!vm) throw new Error('must be called in setup')
  return vm.proxy.$router
}
// 访问route
export const useRoute = () => {
  const vm = getCurrentInstance()
  if (!vm) throw new Error('must be called in setup')
  return vm.proxy.$route
}

// vue 
 import { useStore, useRouter, useRoute } from './../utils/vueApi'

 const router = useRouter()
 router.push('/xxx')