Learn how to dynamically pass a value from a prop to a router-link in Vue.js

I created a custom button component and decided to switch from using <a> tags to <router-link>. However, I encountered an error because the router-link was rendering before the prop received its value. To address this, I added an if statement but I'm seeking a more elegant solution.

<template>
  <input
    v-if="type === 'submit'"
    type="submit"
    class="button"
    :value="$slots.default[0].text"
    :class="{'button--inactive': disabled}"
  />
  <router-link
    v-else-if="type === 'button' && href !== undefined"
    class="button"
    :class="{'button--inactive': disabled}"
    :to="href"
  >
    <slot></slot>
  </router-link>
</template>

<script>
export default {
  name: 'Button',
  props: {
    href: {
      type: String
    },
    type: {
      type: String,
      default: 'button',
      validator: value => ['button', 'submit'].indexOf(value) !== -1
    },
    disabled: {
      type: Boolean
    }
  }
}
</script>

Is there anyone who can offer assistance?

Answer №1

Have you attempted setting a default value for the href prop?

  props: {
    href: {
      type: String,
      default: '#',
    },
  },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to extract values from promises that are still pending?

Having some issues with the code below and unable to achieve the desired output. Any help in identifying what's wrong would be greatly appreciated. Thanks! Here is the code: // Making http requests const getJSON = require('get-json'); ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

Are there any additional performance costs associated with transmitting JSON objects instead of stringified JSON data through node.js APIs?

When developing node.js APIs, we have the option to send plain JSON objects as parameters (body params). However, I wonder if there is some extra overhead for formatting. What if I stringify the JSON before sending it to the API and then parse it back to i ...

The conditional statements within the resize function may not always be triggered when the conditions are fulfilled

Struggling to trigger a function only once when resizing. The issue is that the conditional statements are not consistently executed every time. Here's the code snippet: var old_width = $(window).width(); $(window).on('resize.3col',functio ...

Encountering Problem with Office Object Access in Vue.js Outlook Add-in

Just getting started with vue.js and encountering an issue when trying to access the Office object within Vue methods. In the code snippet below, calling load() from created function works fine, but attempting to call it from this.loadProps() does not wor ...

Creating a dynamic div and populating it with data from various elements in separate xhtml files: a step-by-step guide

I am looking to dynamically add a div under the div tag with id "includedContent" in the code below. Additionally, I would like to modify the load method to accept an array of ids instead of a hardcoded Id(123) and display the data in the dynamically creat ...

Enhance your dynamic php page with the use of a light box feature

Hey, I have created a PHP page that dynamically reads images from a folder and displays them on a gallery page. However, I am facing some issues - I am unable to link an external CSS file and I have to include all the CSS within the HTML. Additionally, I c ...

Show the current phone number with the default flag instead of choosing the appropriate one using the initial country flag in intl-tel-input

Utilizing intl-tel-input to store a user's full international number in the database has been successful. However, when attempting to display the phone number, it correctly removes the country code but does not select the appropriate country flag; ins ...

Validate each string in an array using Vuelidate and show corresponding error messages for each item in Vue.js

I have a project in Vue where I gather test answers using forms. I am trying to validate each input with { required } but I am encountering difficulties. The code below checks if there is an array instead of verifying if each string within the array is pre ...

Why is it that I am unable to properly encode this URL in node.js?

$node querystring = require('querystring') var dict = { 'q': 'what\'s up' }; var url = 'http://google.com/?q=' + querystring.stringify(dict); url = encodeURIComponent(url); console.log(url); Here is the re ...

Generate a new core element featuring the top 10 users

In my app, I have a function that sorts users in the mobile_user table based on their earned points and assigns them a rank. This function is triggered every time an http request is made. Now, what I want to achieve is creating a new root node called lead ...

having difficulty with the design of my google map

Struggling to style my Google Map this week - I have the JSON values but no clue how to add them into the JavaScript. Also, need to move the zoom bar control to the right instead of it being hidden behind site content on the left. Any help would be greatl ...

What is the best way to pass a websocket instance to Vue.js components and then invoke the send() method on it?

I am attempting to send a message via a web socket to the server when a button is clicked: // HelloApp.vue <template> <div class="hello"> <h1>{{ msg }}</h1> <button v-on:click="sendMessage($event)">Send Message< ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

ng-repeat not functioning properly with FileReader

Here is a look at how my view appears: <body ng-controller="AdminCtrl"> <img ng-repeat="pic in pics" ng-src="{{pic}}" /> <form ng-submit="postPic()"> <input id="photos" type="file" accept="image/*" multiple/> <button> ...

Easily toggle between different content within the same space using Twitter Bootstrap Tabs feature. Display the tabs

I made a modification to the bootstrab.js file by changing 'click' to 'hover': $(function () { $('body').on('hover.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.p ...

What reasons could lead to useSWR returning undefined even when fallbackData is provided?

In my Next.js application, I'm utilizing useSWR to fetch data on the client-side from an external API based on a specified language query parameter. To ensure the page loads initially, I retrieve data in a default language in getStaticProps and set it ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

Modify the background color based on the length of the input in Vue

Can you change the background color of the initial input field to green if the value of the Fullname input field is greater than 3 characters? See below for the code: <div id="app"> <input type="text" v-model="fullname" placeholder="Enter Full ...