Home > Software design >  Vue: Passing a link to components prob
Vue: Passing a link to components prob

Time:12-12

why does this doesn't work?

Child-Component:

<template>
    <button  @click="router.push('{{link}}')">{{ text }}</button>
</template>

<script setup lang="ts">
import { defineProps } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

const props = defineProps({
    text: String,
    link: String,
})

</script>

Parent-Component:

`

<Button text="To MainView" link="'/mainview'"></Button>

`

Passing text works, passing link also shows the right String in Console (/mainview) but the link it shows me is http://localhost:8080/{{link}}.

And now I'm confused because in my understanding it should work. Thanks!

CodePudding user response:

In your code, this line @click="router.push('{{link}}')" don't work like that. You can write like this

@click="$router.push(`${link}`)"

Vue Mustache syntex i.e {{}} only work inside HTML tag like

<div>{{val}}</div>

to call an event you can simply run like below

<div @click="any valid js syntex">Hello</div>

CodePudding user response:

You've already defined link as a static prop in your Child Component so you don't have to add single quotes around /mainview:

<Button text="To MainView" link="/mainview"></Button>

It would only be necessary if the prop is a dynamic prop (ex. :link="'/mainview'") but in this case, since you're defining /mainview directly into the prop then you can omit the single quotes (Static Props vs Dynamic props). Additionally, you can pass link directly to the @click event like so:

<button  @click="router.push(link)">{{ text }}</button>

or just use router-link instead:

<router-link :to="link">
    <button >{{ text }}</button>
</router-link>
  • Related