1

Well, this is my App.vue:

    <template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <Home/>
    <AddService/>
  </div>
</template>

<script>
import Home from './components/Home.vue'
import AddService from './components/AddService.vue'
import Vue from 'vue'
import VueRouter from 'vue-router'

const router = new VueRouter({
    mode: 'history',
    routes: [
        {
            path: '/home',
            name: 'home',
            component: Home
        },
         {
            path: '/addService',
            name: 'addService',
            component: AddService
        }
    ]
});
        
Vue.use(router)


export default {
  name: 'App',
  components: {
    Home
  }
}
</script>

I'd like to route between the Home and AddService Component. My Home page has a link which is basically this: <a href="../addService">Add a new Service</a>

And if I press on this link I should get redirected to the AddService Component. But at the moment it only adds the right url in the search bar but I don't get redirected

2 Answers 2

1

When using Vue router you are not supposed to make your own anchor tags with hrefs for navigation. To navigate you can use the router-link component.

If you want to programmatically navigate you can use the push method on the router.

Sign up to request clarification or add additional context in comments.

Comments

1

Your App.vue should look like this

<template>
    <div id="app">
        <router-view />
    </div>
</template>

Your index.js should look like this

import Vue from 'vue'
import App from '@/App.vue'
import VueRouter from 'vue-router'
import Home from '@/components/Home'
import AddService from '@/components/AddService'

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/add-service',
        name: 'Add Service',
        component: AddService
    }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})


new Vue({
    el: '#app',
    router,
    render: h => h(App)
}).$mount('#app')

BUT best practise is to use an external router/index.js file to declare all your routes and import to the index.js(main app file) and use it when you declare new Vue instance.

After that you can have router-link in your code as

<router-link to="path">

or navigate programmaticaly with

this.$router.push({ name: AddService })

or

this.$router.push({ path: '/' })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.