Home > front end >  create a route with vue router
create a route with vue router

Time:11-30

I have some issues creating a router using router on vuejs. My file main.js was just like the code below and then when I changed to add some routes I got the error below

MAIN.JS BEFORE (WORKING WELL)

import 'bootstrap/dist/css/bootstrap.css'
import { createApp } from 'vue'
import Vue from 'vue'
import App from './App.vue'
import router from './router'
    
import VueRouter from 'vue-router'
import store from './store'
    
createApp(App).use(store).use(router).mount('#app')

MAIN.JS AFTER

import 'bootstrap/dist/css/bootstrap.css'
import Vue from 'vue'
import App from './App.vue'

import VueRouter from 'vue-router'
import store from './store'

import testeRouter from './pages/testeRouter'

Vue.use(VueRouter)

const router = new VueRouter({
    routers: [
        {
            path: '/pages/testeRouter',
            component: testeRouter
        }
    ]
})

Vue.createApp(App).use(store).use(router).mount('#app')

ERROR

TypeError: Cannot read properties of undefined (reading 'use')

The pages don't render anymore. I've been a while trying to fix it. Anyone knows what it could be? Thanks

{
  "name": "routing-software",
  "version": "0.1.0",
  "lockfileVersion": 2,
  "requires": true,
  "packages": {
    "": {
      "name": "routing-software",
      "version": "0.1.0",
      "dependencies": {
        "axios": "^0.27.2",
        "bootstrap": "^5.2.1",
        "bootstrap-vue": "^2.22.0",
        "core-js": "^3.8.3",
        "router": "^1.3.7",
        "vue": "^3.2.40",
        "vue-axios": "^3.4.1",
        "vue-router": "^4.0.3",
        "vuex": "^4.0.0"
      },
      "devDependencies": {
        "@babel/core": "^7.12.16",
        "@babel/eslint-parser": "^7.12.16",
        "@vue/cli-plugin-babel": "~5.0.0",
        "@vue/cli-plugin-eslint": "~5.0.0",
        "@vue/cli-plugin-router": "~5.0.0",
        "@vue/cli-plugin-vuex": "~5.0.0",
        "@vue/cli-service": "~5.0.0",
        "eslint": "^7.32.0",
        "eslint-plugin-vue": "^8.0.3"
      }
},

CodePudding user response:

Vue 3 does not have direct access use method. That's the issue.

Vue.use(VueRouter) // this is the issue

Try like this

import 'bootstrap/dist/css/bootstrap.css'
import { createApp } from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

import store from './store'

import testeRouter from './pages/testeRouter'

const router = VueRouter.createRouter({
    routers: [
        {
            path: '/pages/testeRouter',
            component: testeRouter
        }
    ]
})

createApp(App).use(store).use(router).mount('#app')

Checkout Vue 3 route handling here & Breaking changes here

  • Related