I'm trying to integrate Vue Router in my Vue porject.
To do this I installed the package with npm install vue-router@4
.
In my main.js
I integrated the router like this:
import Vue from 'vue'
import App from './App.vue'
// Router
import * as VueRouter from 'vue-router';
import StartNovice from './components/Novice/StartNovice';
const routes = [
{
path: '/novice',
name: 'novice',
component: StartNovice
}
]
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: routes,
})
Vue.use(VueRouter);
new Vue({
router: router,
render: h => h(App),
}).$mount('#app')
Then I tried creating a link in App.vue
like this:
<router-link to="/novice">Link Text</router-link>
<router-view></router-view>
However, I'm getting
[Vue warn]: Unknown custom element: <router-link> - did you register the component correctly?
[Vue warn]: Unknown custom element: <router-view> - did you register the component correctly?
Well, apparently I did not!
The Docs say Make sure to _use_ the router instance to make the whole app router-aware
. Therefore I tried changing Vue.use(VueRouter);
to Vue.use(router);
, but this makes things worse:
Uncaught TypeError: Cannot set properties of undefined (setting '$router')
What am I doing wrong? Thanks!
Vue router 4 is compatible with Vue 3 which has a different syntax than Vue 2 :
import {createApp} from 'vue'
import App from './App.vue'
// Router
import * as VueRouter from 'vue-router';
import StartNovice from './components/Novice/StartNovice';
const routes = [
{
path: '/novice',
name: 'novice',
component: StartNovice
}
]
const router = VueRouter.createRouter({
history: VueRouter.createWebHashHistory(),
routes: routes,
})
createApp(App).use(router).$mount('#app')
Make sure to install the Vue version 3