Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass href value to template in Vue

This is the HTML.

<navlink v-bind:href="#about">About</navlink>

And the main.js code is

Vue.component('navlink', {
    template: '<li class="item"><a><slot></slot></a></li>'
});

But I'm getting error

[Vue warn]: failed to compile template: - invalid expression: v-bind:href="#about"

How to fix this?

like image 521
anoop chandran Avatar asked Feb 05 '23 11:02

anoop chandran


1 Answers

I realise that you have solved this, but v-bind expects you to be pointing to an object in your parent class's data and you are trying to use a string literal, so Vue throws an error because it cannot find an object with that key.

You may also prefer to pass href as a prop to your component instead, so you end up with:

Vue.component('navlink', {
    template: '<li class="item"><a :href="href"><slot></slot></a></li>',
    props: ['href']
});

and then you can just do:

<navlink href="#about">About</navlink>

Here's the JSFiddle: https://jsfiddle.net/ov94tg5z/

like image 135
craig_h Avatar answered Feb 08 '23 10:02

craig_h