Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable component to render button or router-link in Vue.js

Tags:

vue.js

I'm new using Vue.js and I had a difficulty creating a Button component.

How can I program this component to conditional rendering? In other words, maybe it should be rendering as a router-link maybe as a button? Like that:

<Button type="button" @click="alert('hi!')">It's a button.</Button>
// -> Should return as a <button>.

<Button :to="{ name: 'SomeRoute' }">It's a link.</Button>
// -> Should return as a <router-link>.
like image 760
Caio Tarifa Avatar asked Oct 20 '25 21:10

Caio Tarifa


1 Answers

You can toggle the tag inside render() or just use <component>.

According to the official specification for Dynamic Components:

You can use the same mount point and dynamically switch between multiple components using the reserved <component> element and dynamically bind to it's is attribute.

Here's an example for your case:

ButtonControl.vue

<template>
  <component :is="type" :to="to">
    {{ value }}
  </component>
</template>

<script>
export default {
  computed: {
    type () {
      if (this.to) {
        return 'router-link'
      }

      return 'button'
    }
  },

  props: {
    to: {
      required: false
    },
    value: {
      type: String
    }
  }
}
</script>

Now you can easily use it for a button:

<button-control value="Something"></button-control>

Or a router-link:

<button-control to="/" value="Something"></button-control>

This is an excellent behavior to keep in mind when it's necessary to create elements that may have links or not, such as buttons or cards.

like image 124
Hugo Demiglio Avatar answered Oct 26 '25 03:10

Hugo Demiglio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!