2

How do I load a component in the <router-view> when the page by default on that page? I want to have a default when there is no :id

 <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>


    <div id="app">
        <p>
            <router-link to="/product">/product</router-link>
            <router-link to="/product/foo">/product/foo</router-link>

        </p>
        <router-view>

        </router-view>
    </div>
    <script>
    const Product = {template: `<div class="user"> <h2>User {{ $route.params.id }}</h2></div> `}

    const router = new VueRouter({

    routes: [
        {
            path: '/product/:id', component: Product, 
        }
    ],

    mode: 'history',

    })

    const app = new Vue({ 
        router 
    })

    .$mount('#app')

    </script>
2
  • Use optional parameter. path: '/product/:id? Commented Jan 10, 2019 at 22:52
  • In the component you can also specify default values Commented Jan 10, 2019 at 22:55

1 Answer 1

1

For the vue router you can use optional parameter.

So instead of path: '/product/:id' you can write path: '/product/:id? (added ? at the end)

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
    <p>
        <router-link to="/product">/product</router-link>
        <router-link to="/product/foo">/product/foo</router-link>
    </p>

    <router-view></router-view>
</div>

<script>
    const Product = {
        /*
            router `id` will be passed as prop
            so we can use `id` in our templates instead of $route.params.id
            this way we can also specify the default value is nothing was passed
         */
        template: `<div class="user"> <h2>User {{ id }}</h2></div> `,
        props: {
            id: {
                type:    String,
                // specify default value if id is not passed to the router
                default: 'N/A'
            }
        }
    }

    const router = new VueRouter({
        mode: 'history',
        routes: [
            {
                // :id? means that it's an optional parameter
                path: '/product/:id?',
                component: Product,
                // Passing Props to Route Components
                props:     true
            },
        ],
    })

    const app = new Vue({
        router
    })
    .$mount('#app')

</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know how I could make that template in const Product an external file?
This answer should help

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.