# vue-router和vuex在Vue3中的使用

Vue3中setup是不能使用this访问的,所以之前this.$routethis.$store是不能继续使用的,而要使用新的方式,vue-router和vuex插件内部使用provideinject依赖注入并暴露一个组合函数。

# vue-router使用

看看vue-router的中useApi.ts源码:

import { inject } from 'vue'
import { routerKey, routeLocationKey } from './injectionSymbols'
import { Router } from './router'
import { RouteLocationNormalizedLoaded } from './types'

export function useRouter(): Router {
  return inject(routerKey)!
}

export function useRoute(): RouteLocationNormalizedLoaded {
  return inject(routeLocationKey)!
}

很明显this.$routerthis.$route替代方案就是上面两个函数,在Vue3项目中直接使用:

import { useRouter, useRoute } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()
  }
}

vue-router钩子函数定义在路由配置里面:

[{
  path: "/",
  name: "Home",
  component: {
    ...Home,
    beforeRouteEnter(to, from, next) {
      next()
    }
  }
}]

# vuex使用

vuex暴露了useStore函数在setup中使用:

import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
  setup () {
    const store = useStore()

    return {
      count: computed(() => store.state.count), // state
      evenOrOdd: computed(() => store.getters.evenOrOdd), // getters
      increment: () => store.commit('increment'), // commit
      decrement: () => store.dispatch('decrement') // dispatch
    }
  }
}