How can I connect an image to a link in Vue.js?

I am having trouble linking to another URL when I click on an image using Vue.

It should be possible to link by clicking on the images, but it seems to not be working.

If anyone can offer assistance, I would greatly appreciate it.

Below is what my code looks like:

HTML

<section class="bg-light page-section" id="portfolio">
    <div class="container">
      <div class="row">
        <div class="col-lg-12 text-center"><br>
          <h2 class="section-heading text-uppercase works-text">Works</h2>
          <h3 class="section-subheading text-muted">Selected work that has been created with the help of many.</h3>
        </div>
      </div>
      <div class="row">
       <div class="col-md-4 col-sm-6 portfolio-item" v-for="(obj, key) in portfolioJSON" :key="key"  >
          <a class="portfolio-link" data-toggle="modal" target = "_blank" v-bind:href="`${obj.url}`">
            <div class="portfolio-hover">
              <div class="portfolio-hover-content">
                <!-- <! <i class="fas fa-plus fa-3x"></i> -->
              </div>
            </div>
            <img :src="`${obj.img}`" class="img-fluid" >
          </a>
          <div class="portfolio-caption works-text">
            <h4 class="works-text">{{ obj.caption }}</h4>
            <p class="text-muted works-text">{{ obj.title }}</p>
          </div>
        </div>

      </div>
    </div>
  </section>
export default {
    data() {
      return{
        portfolioJSON: [
           {
                img: require('../assets/img/sukimatch/sukimatch.png'),
                caption: 'Sukimatch',
                title: 'WEBSITE, BANNER DESIGN',
                url: "https://sukimatch-f887f.firebaseapp.com/"
            },
            {
                img: require('../assets/img/portfolio/greencosjapan.png'),
                caption: 'Greencosjapan',
                title: 'WEBSITE',
                url: "https://greencosjapan.com"
            }
        ]
    }
    }, computed: {
    imageArray: function() {
        return this.portfolioJSON.map(obj => obj.img)
    },
    urlArray: function() {
        return this.portfolioJSON.map(obj => obj.url)
    }
},

}

Answer №1

Your current code will not function correctly in that manner. You should use ${obj.img}, as this is the updated ES6 syntax for template literals.

<div class="col-md-4 col-sm-4 sk-item" v-for="(obj, key) in portfolioJSON" :key="key">
          <img :src="`${obj.img}`" class="img-fluid" alt="" >
        </div>

To learn more about this syntax, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

It's highly beneficial; consider implementing it wherever possible in your code.

img: require('../assets/img/sukimatch/sukimatch.png'),
                caption: 'Sukimatch',
                title: 'WEBSITE, BANNER DESIGN',
                url: "https://sukimatch-f887f.firebaseapp.com/"

:title="`${obj.title}`"
:href="`${obj.url}`"
:img="`${obj.img}`"

I hope this information proves helpful to you :)

Update:

    export default {
      data() {
            return {
               portfolioJSON: [
               {
                    img: require('../assets/img/sukimatch/sukimatch.png'),
                    caption: 'Sukimatch',
                    title: 'WEBSITE, BANNER DESIGN',
                    url: "https://sukimatch-f887f.firebaseapp.com/"
                },
                {
                    img: require('../assets/img/portfolio/greencosjapan.png'),
                    caption: 'Greencosjapan',
                    title: 'WEBSITE',
                    url: "https://greencosjapan.com"
                }
            ]
}, computed: {
        imageArray: function() {
            return this.portfolioJSON.map(obj => obj.img)
        }
    }

}

Answer №2

There is no need for an href attribute on your image tag. Your current code seems like it should work fine. I tested a similar example on a codepen and it worked perfectly. Try sharing a codepen with a more comprehensive example, as the issue could be related to CSS.

Your original code:

<img :src="obj.img" class="img-fluid" href="obj.url">

Updated code:

<img :src="obj.img" class="img-fluid"

Answer №3

This method really saved the day for me. Especially when the asset folder is situated within the public directory.

<div style="backgroundImage: url('~../../assets/images/image_1.jpg')">

However, if the asset folder is located within the src directory, remember to use the alias "@".

<div style="backgroundImage: url('~@/assets/images/image_1.jpg')">

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

How to access the CSS and JS files in the vendor folder using linemanjs

Currently, I am in the process of developing a web application utilizing linemanjs. However, I have encountered an issue where the vendor css and js files are not being referenced correctly when explicitly included. I would appreciate any guidance on what ...

Error in Node.js React: Unable to add context property as the object is not extendible

Currently, I'm in the process of integrating an isomorphic react component into my node.js + express setup. However, as I attempt to add the component to my jade template for rendering, I encounter this error: TypeError: Can't add property contex ...

What is the reason that .every() is not recognized as a function?

I have gathered a collection of required form elements and have added a 'blur' listener to them. var formInputs = $(':input').filter('[required]'); formInputs.each(function(i) { $(this).on('blur', function ...

Setting the number of search results displayed per page on Algolia autocomplete can be done by

According to the documentation on autocomplete, it mentions the following about hits: Hits To create a source based on Algolia's hits array, simply use: { source: autocomplete.sources.hits(indexObj, { hitsPerPage: 2 }), templates: { sugge ...

Tips on changing an image with a button click

I am currently working on a project where I have a div tag containing an image that is selected randomly from different arrays based on topics. However, I am facing some challenges in making the image change when the "go" button is clicked. I want the if ...

Tips for testing views in ember.js using unit tests

We are currently delving into the world of Ember.js. Our development process is completely test-driven, and we aim to apply the same methodology to Ember.js. Having prior experience in test-driven development with Backbone.js apps using Jasmine or Mocha/Ch ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

Listen for the modified value in a directive with AngularJS

I am currently working on implementing a directive that can draw a chart based on specified values. What I am aiming for is to pass the data necessary for the plot directly from the template rather than using ng-model, as my current solution requires. I ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

Ways to correct inverted text in live syntax highlighting using javascript

My coding script has a highlighting feature for keywords, but unfortunately, it is causing some unwanted effects like reversing and mixing up the text. I am seeking assistance to fix this issue, whether it be by un-reversing the text, moving the cursor to ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Integrate items into an array using a specified structure

In my code, there is an array called $paises: Array ( [0] => Array ( [life_sciences] => Array ( [0] => Array ( [value] => Life Scie ...

The DELETE request in my app using React Native and Fetch API is experiencing difficulties, although it is successfully working when tested in

We are facing an issue with our API while querying through React Native. Surprisingly, GET and POST requests work perfectly fine in both our app and Postman. However, the DELETE functionality seems to be failing on the app, even though the same request w ...

Test results indicate successful completion of tests for VueJS component files, however code coverage does not reflect this for those

Currently, I am facing an issue while trying to obtain code coverage results for my VueJS frontend application. It seems that when I create a component and write a snapshot test for it, the file is being ignored by WebStorm. After some investigation, I di ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

Tips for resolving jQuery conflict problems

I am dealing with a jQuery issue where I have two scripts - one for the slider and the other for a dropdown menu. When I remove one script, the slider works but the dropdown doesn't, and vice versa. I have looked at tutorials online on how to resolve ...

Having trouble registering Vuex modules? It could be because the namespaces are not being found or the getters.default property is

I've hit a roadblock while setting up Vuex modules for my latest project. I attempted to follow Chris Fritz's example of registering components in a more efficient manner, as demonstrated in this video: https://www.youtube.com/watch?v=7lpemgMhi0k ...

What is the correct way to interpret the URL of attachments in messages?

I'm trying to create a feature where, when someone sends an image or a link of an image (like with Imgur), the attachment's URL gets logged in a specific channel. I attempted to achieve this using if(message.attachments.length > 0 || message. ...

Retrieve the value either from the $.postJSON function or patiently wait for it to complete

My current challenge involves making a JSON post to the server and retrieving only one boolean value. The issue is that this JSON call is nested within another function, which also needs to return the boolean. I am considering two possible solutions: Th ...

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...