What is the best way to pass a URL in Vue.js methods and activate it on @click event?

Currently, I am working on a Laravel Vue.js project where I am trying to implement a method to redirect to a link upon clicking a div element. The code snippet provided below showcases my approach. When the user clicks on the div, I want them to be directed to the site (www.google.com). Despite exploring various solutions from similar forum posts, I have been unsuccessful in achieving this functionality.

<template>
    <div style="cursor:pointer;" @mouseover="showMe" @mouseout="hideMe" @click="goToMySite">
        <h6 v-show="goTolink === false">Hover Me</h6>
        <h6 v-show="goToLink === true"> Click to visit My Site </h6>
    </div>
</template>
    
<script>
export default {
    props: [],
    
    data() {
        return {
            goTolink: false,
        }
    },

    methods: {
        showMe(){
            this.goTolink = true
        },
    
        hideMe(){
            this.goTolink = false
        },
    
        goToMySite(){
            href='http://www.google.com'
        }
    }
}
</script>
    
<style>
    
</style>

Answer №1

It seems there are several issues in your code that need attention.

  • The listeners are not placed correctly. Placing them on the parent container makes the link invisible since its parent is no longer displayed.
  • Consider using mouseenter / mouseleave instead of mouseover / mouseout to avoid unnecessary events being triggered.
  • In this scenario, it is recommended to utilize v-if / v-else rather than v-show.
  • The href attribute is missing in your goToMySite method.

Here is an improved example:

<template>
    <div style="cursor:pointer;">
        <h6 v-if="!goTolink"
            @mouseenter="showMe">Hover Me</h6>
        <h6 v-else
            @mouseleave="hideMe"
            @click="goToMySite">Click to visit My Site</h6>
    </div>
</template>

<script>
export default {
    props: [],
    data() {
        return {
            goTolink: false,
            href: 'https://www.google.com'
        }
    },
    methods: {
        showMe() {
            this.goTolink = true
        },
        hideMe() {
            this.goTolink = false
        },
        goToMySite() {
            // Implement your desired functionality here, for instance
            window.open(this.href, '_blank');
        }
    }
}
</script>

Snippet (window.open functionality may not work):

<!DOCTYPE html>
<html>

<!-- Omitted for brevity -->

</html>

Some additional tips:

  • Avoid using inline styles whenever possible.
  • To check if a value exists or not, you can use !value (and simply value to check if the variable is defined).
  • Consider using an a tag styled as an h6 element for links in such cases.

You have other options to handle the change in goToLink value. For instance, directly in the template:

<h6 v-if="!goTolink"
    @mouseenter="goTolink = true">Hover Me</h6>
<h6 v-else
    @mouseleave="hideMe"
    @click="goTolink = false">Click to visit My Site</h6>

Or consolidate the toggle logic into one method:

<h6 v-if="!goTolink"
    @mouseenter="toggleLink">Hover Me</h6>
<h6 v-else
    @mouseleave="toggleLink"
    @click="toggleLink">Click to visit My Site</h6>
methods: {
    toggleLink() {
        this.goTolink = !this.goTolink;
    }
}

Answer №2

Utilize the window object's location attribute.

redirectToMyPage(){
    window.location.href='http://www.yahoo.com'
}

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

Enhance the structure of information retrieved from the API

Recently I sought advice on formatting API data and received some excellent responses. However, I encountered an error when the API lacked data for certain assets: https://i.stack.imgur.com/HgJDd.png Here is an example without the highlighted code: http ...

The dynamic ID selector is failing to execute or initialize

Currently, I am in the process of developing a jQuery function that involves dynamically adding new <tr id="select_row"> tags. Each new tag will have an incremented ID such as select_row1, select_row2, select_row3. After successfully increasing the ...

Passing $index variable from a bootstrap modal window does not work in AngularJS

I'm running into a wall here. My issue involves using ng-repeat to populate a table with two buttons in each row - one for updating the row content and another for uploading files. The upload button triggers a bootstrap modal window where users can se ...

ng-class does not seem to be functioning properly when used within a file that is included via ng-include in

My question pertains to the menu I am loading using ng-include from the index file. <span ng-include="'app/components/common/menu.html'"></span> The content of menu.html is as follows: <li ng-class="active" > <a hr ...

Superimpose a canvas onto a div element

I'm struggling to overlay a canvas on top of a div with the same dimensions, padding, and margins. Despite using position: absolute and z-index as suggested in similar questions, the canvas keeps appearing underneath the div. Here's my current co ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...

The error occurred in async JavaScript parallel code because the task is not recognized as a function

I am attempting to upload an image and update the image URL in the database collection using the code provided below. Controller.prototype.handle = function (req, res, next) { var id = req.params.id, controller = req.params.controller, optio ...

Issue: The function connect.compress is not defined

I am currently working on a project that is primarily written in TypeScript and then transpiled into JavaScript. The backend is built with Node, while the frontend uses React Native. Recently, after updating to Babel6, we started encountering numerous erro ...

Navigate to a specific section of a webpage with automatic scrolling

I'm developing a Chrome App and incorporating the web view tag, which functions similarly to an iframe. Is there a way to load a webpage inside the web view halfway down the page? I have attempted the following: application.js: $(document).ready(f ...

Jquery solution for toggling multiple Divs individually

I'm currently working on a small application that has both a sidebar menu and a header menu. My goal is to have all items in these menus toggle the visibility of content in one main window or page. When a button is clicked, I want it to show the corre ...

The eccentricities of Angular Translate in Firefox and Safari

While everything functions correctly in Chrome, there seems to be an issue with changing the language in Safari and Firefox. angular.module('angularApp') .config(['$translateProvider', function ($translateProvider) { $translateProv ...

Utilize a specific component to enclose particular words within a contenteditable div in an Angular project

I have a task at hand where I need to manipulate text input from a contenteditable division, use regex to identify specific words, and then wrap those words within an angular component. Although I have managed to successfully replace the text with the com ...

Transferring information submitted in a form to a service using AngularJS

Trying to implement a shopping cart app where I need to pass an object into a service function using Angular. Following advice from another post, but encountering an unprovided error and a strange syntax error on page load. The issues seem to be originatin ...

How can I access the value of a textbox within a dynamically generated div?

In my project, I am dynamically creating a div with HTML elements and now I need to retrieve the value from a textbox. Below is the structure of the dynamic content that I have created: <div id="TextBoxContainer"> <div id="newtextbox1"> // t ...

Unable to display D3.js bar graphs

Hello! I'm attempting to replicate a bar chart from this source but unfortunately, my bars are not displaying properly. I'm confident that I've inputted the correct values for the y and height parameters. Could someone kindly assist me with ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

In a Vue serverless web application, OpenLayers Map object fails to trigger events

In my Vue serverless web application, I have implemented an OpenLayers map initialized in the mounted lifecycle method. The map is populated with ImageWMS layers that are updated by various functions. After updating the parameters of these layers, I call ...

The onCall function in Firebase's realtime database does not provide a response data object when executing the remove() operation

When using onCall to perform a remove operation from a realtime database, I encountered an issue where the response only returned null instead of the expected data object. Strangely, I have used onCall for other operations like update and always received a ...

Does the global $.ajaxSetup() function not impact $.ajax() calls within distinct functions?

Is it possible to make the effects of $.ajaxSetup() reach into function bodies? I'm having trouble getting $.ajaxSetup() to impact the $.ajax() calls within functions. Here is an example: In the code snippet below, the ajax request made by function f ...

The jQuery mouseout functionality seems to be malfunctioning and not responding as expected

I am currently developing a slider that displays details when the mouse hovers over the logo, and hides the details when the mouse moves away from the parent div. jQuery('.st_inner img').mouseover(function() { jQuery(this).parent().siblings( ...