Using an image as a button in Vue.js: A step-by-step guide

I'm currently working on creating a login button within a single-file-component using Vue.js in my Rails application with a Vue.js front-end. The purpose of this button is to redirect users to an external login page when clicked.

I am wondering how I can incorporate an image as the button itself. My assumption is that I would need to utilize v-on:click for the redirection functionality, but I am unsure how to proceed from there.

At the moment, the code I have displays a static button that includes the path to an image like

img(src="../assets/img/login_button.png")
. Clicking on this button does not display the actual image as intended. Instead, only the path is visible.

// LoginButton.vue

<template lang="pug">
#login-button
  <button v-on:click="redirect_to_login">img(src="../assets/img/login_button.png")</button>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';

@Component
export default class LoginButton extends Vue{
  redirect_to_login():void{ // This method has not been implemented yet 
  }
}
</script>

Answer №1

Instead of incorporating an HTML image in your button, have you considered using a different approach? I am not familiar with pug.

<button v-on:click="redirect_to_login"><img src="../assets/img/login_button.png" /></button

You could potentially eliminate the button altogether since you are working with Vue and not a traditional HTML form. Simply bind the click event directly to the image instead.

<img src="../assets/img/login_button.png" v-on:click="redirect_to_login" />

Answer №2

I am not well-versed in pug, so I'm unsure of the specific syntax you'll need. However, you can utilize the <router-link> tag to define the route. For instance (using Vuetify)

    <router-link to="/">
      <v-img src="/path/to/img.gif"/>
    </router-link>

Answer №3

To achieve the desired outcome, you have two options:

<a @click="Redirect">
     <img src='IMAGE_SRC'  />
  </a>

or

<img @click="Redirect" src='IMAGE_SRC'/>


new Vue({
            el: '#app',
            methods:
            {
               Redirect()
                  {
                     window.location.href = "https://example.com/";

                     //or 

                      //this.$router.push('LINK_HERE'); // if you are using a router
                  }
               }
      })

Check out the demo link below:

https://example.com/demo-link/

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 proper way to include 'rowspan' specific CSS within an HTML table?

I have an HTML table with rowspans in it: table tr, td { border: 1px solid black; } tr:nth-child(1) { background-color: red; } tr:nth-child(2) { background-color: blue; } <table> <tr> <td rowspan=2>Section 1</td> ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

Is it possible to assign a property value to an object based on the type of another property?

In this illustrative example: enum Methods { X = 'X', Y = 'Y' } type MethodProperties = { [Methods.X]: { x: string } [Methods.Y]: { y: string } } type Approach = { [method in keyof Method ...

How can you troubleshoot code in NextJS API routes similar to using console.log?

Incorporating nextjs API routes into my upcoming project has been a priority, and I recently encountered an issue with code execution upon sending a POST request. Debugging has proven to be challenging since I am unable to use conventional methods like co ...

What is the best way to fetch data for each specific ID using axios.post when making a URL call?

Utilizing Axios to fetch data from an API and display them as cards in a movie component, I am facing the challenge of enabling users to click on a single movie card and navigate to another page (singlepage.vue) with the corresponding movie ID from the API ...

The back-end code on the server is unable to identify the variable in my req.body, as it is being flagged

At the moment, I am in the process of developing a web application that needs to transmit data from the client side to the server side whenever a specific button is clicked. However, when I click the button, the terminal consistently informs me that the va ...

I'm unable to resolve all parameters for xxx -- unit testing using jest

I recently encountered an issue with a test in jest that is failing and displaying the following error message: Error: Can't resolve all parameters for LoginService: (?). at syntaxError (/Users/wilson.gonzalez/Desktop/proyecto_andes/external/npm/nod ...

Extract and preserve elements from an ordered array by segregating them into separate arrays of objects using Angular 8

I have an array called arrayReceived containing 15 objects. My goal is to sort and store the first 6 objects with the lowest amount value in a new array called arraySorted. These objects are sorted based on their amount parameter. There may be multiple obj ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

Retrieving a result from a function call is a fundamental aspect of programming

I have a scenario where I am initiating a call from a controller within AngularJS. This call passes some data to a service in order to receive a response that needs to be conditionally checked. Controller patents.forEach(function(item){ // The "patents" ...

Delete outdated information using Google Apps Scripts when the date is less than the current date plus a specified number of days

I have a Google Sheet where I need to filter out entries based on the number of days since the last check. Specifically, I want to keep only those entries where the number of days since the last check is greater than 10. You can find the Sheet here. fu ...

Guide on automatically inserting a colon (:) after every pair of characters in Angular

I am looking to automatically insert a colon (:) after every 2 characters in my input field: HTML <input nz-input type="text" appLimitInput="textAndNumbers" name="mac" formControlName="mac" (keydown.space)=&qu ...

`The Importance of Validating Enum Arrays in Typescript Using Class-Validator`

Is there a way to validate an array of enums in a DTO without getting misleading error messages? Here is an example of my DTO: import { IsArray, IsEmail, IsEnum, IsIn, IsNotEmpty, IsString } from "class-validator"; import { UserAction, UserModul ...

Having difficulty storing duplicate requests that are crucial for various services/components

Currently, I am tackling a project that involves displaying multiple sets of data to the user. Each set requires several requests to be made to the backend. Specifically, for the UserDetails dataset, I must query the getUser and getSigns endpoints. However ...

Exploring the differences in performance between React hooks and React classes

Currently, I am delving into understanding React hooks and could use some assistance with comprehending whether every time a React function renders, the hook state resets. Below is a brief example related to fixing a header on scroll: class Header extends ...

The domain retrieval is contingent on the language preference of the user

A task has been assigned to create a script in JavaScript/jQuery (or other suitable technologies) that will return a domain with a .pl extension if the user's browser language is set to Polish. Otherwise, the script should return a .eu domain extensio ...

You cannot use the "this" keyword outside of a class body

I am facing an issue with my function, can someone help me? Here is the code: function remove_multi_leg(): void { if (Number($("#search_no_legs").val()) < 2) { return; } const removeId: number = Number($(this).attr("data-number")); const ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

In Angular 2, I am having trouble reaching the properties of an object nested inside another object

I have a variable named contact. When I used console.log(contact) to display its contents, this is what I got: addresss:[] company:"" emails:[] id:3 internet_calls:[] lat:"10.115730000000001" lng:"76.461445" name:"Diji " phones:[] special_days:[] timesta ...

AngularJS: Toggle footer visibility with custom message

My goal is to develop an Angular app using Intel XDK with 3 page scripts in index.html, each having a separate footer. The requirement is for the footer and its message to display and hide every 5 seconds when running each page. app.js app.controller(&ap ...