I have been attempting to implement attribute binding on an image in Vue.js, however, the functionality is not

I am working on a vuejs cli project where I am trying to display images in the order of @mouseover events and link them with IDs, but for some reason it is not recognizing the image.

export default {
    data() {
        return {
            cart: 0,
            imagestitle: "cat",
            images: "./socks_green.jpg",
            variants: [
                { id: 1, color: "green", image: "../assets/images/socks_green.jpg" },
                { id: 2, color: "blue", image: "../assets/images/socks_blue.jpg" },
                { id: 3, color: "blue", image: "../assets/images/socks_blue.jpg" },
                { id: 4, color: "blue", image: "../assets/images/socks_blue.jpg" },
                { id: 5, color: "blue", image: "../assets/images/socks_blue.jpg" },
                { id: 6, color: "blue", image: "../assets/images/socks_blue.jpg" },
            ],
        };
    },  methods: {
        updateImage(variantImage) {
            this.image = variantImage;
        },
    },

For example:

<div class="images"></div>
    <img :src="images" :alt="imagestitle" />
    <div>add<div
        v-for="variant in variants"
        :key="variant.id"
        :mouseover="updateImage(variant.image)"
    >
        {{ variant.color }}
    </div>
    <div>{{ cart }}</div>
    <button :click="adTo">addd</button>
</div>

view the image here

Answer №1

To organize images in a List, include the image name with a slash like this: { id: 1, color: "green", image: "/socks_green" }.

When using a template: <img :src="../assets/images${images}.jpg

" :alt="imagestitle" /> 

Alternatively, consider moving all images to a static folder and reference them like so:

<img :src="${images}.jpg

" :alt="imagestitle" /> 

Answer №2

Below is the code snippet that can help you change images on mouseover without using methods.

  1. Create a variable called imageIndex in your data()
  2. When hovering over an element in a loop (v-for), assign the index to the imageIndex variable
  3. In the img tag, use a condition in :src which checks if imageIndex is null and displays an image from either images or variants array based on the index
  4. Reset the imageIndex to null on mouseleave (optional feature for reverting back to default image)

HTML:

<div class="images"></div>
  <img :src="imageIndex !== null ? variants[imageIndex].image : images" :alt="imagestitle" />
    <div
      v-for="(variant, index) in variants"
      :key="variant.id"
      @mouseover="imageIndex = index"
      @mouseleave="imageIndex = null"
    >
       {{ variant.color }}
    </div>

    <div>{{ cart }}</div>

    <button @click="adTo">addd</button>
</div>

JavaScript:

data() {
  return {
      imageIndex: null,
      cart: 0,
      imagestitle: "cat",
      images: "./socks_green.jpg",
      variants: [
         { id: 1, color: "green", image: "../assets/images/socks_green.jpg" },
         { id: 2, color: "blue", image: "../assets/images/socks_blue.jpg" },
         { id: 3, color: "blue", image: "../assets/images/socks_blue.jpg" },
         { id: 4, color: "blue", image: "../assets/images/socks_blue.jpg" },
         { id: 5, color: "blue", image: "../assets/images/socks_blue.jpg" },
         { id: 6, color: "blue", image: "../assets/images/socks_blue.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

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...

An unexpected error occurs when attempting to invoke the arrow function of a child class within an abstract parent class in Typescript

Here is a snippet of code that I'm working on. In my child class, I need to use an arrow function called hello(). When I try calling the.greeting() in the parent class constructor, I encounter an error: index.ts:29 Uncaught TypeError: this.hello is ...

Copying JSON Data in JavaScript: A Guide

Seeking advice on how to duplicate JSON within the same JSON at various hierarchy levels. Take a look at this example JSON below: Initial code snippet looks like this: { "data": { "moduleName": { "content": { "modul ...

Refreshing the current checkbox input field in React

I developed a unique custom weekdays check input field using React.js to display which days are open for customers. By looping through a hardcoded array, each day is rendered with its corresponding input checkbox. The first row shows Monday through Thursda ...

Utilizing Scala for Converting an Array of Strings into a Case Class

I have defined a case class as shown below: def case_class(): Unit = { case class StockPrice(quarter : Byte, stock : String, date : String, open : Double, high : Do ...

Implementing a download hyperlink attribute for a button with jQuery

How can I create a jQuery function for a button? <input type="submit" id="submit"></input> Once clicked, it should trigger the following action: <a download href="file.doc"></a> <script> $("#submit").click(function(){ ...

Leverage the Ajax response within a Jade template

I'm currently utilizing ExpressJS with the Jade template engine. My goal is to achieve the following: Within a Jade file, I need to extract a variable that will be used in a JavaScript file. This JavaScript file will then make an Ajax request to the ...

"Exciting developments in Angular 17 with the introduction of the new @

I need to output elements from an array of strings starting at index 1. arr = [ "str1", "str2", "str3", "str4", "str5" ] The desired output is: str2 str3 str4 str5 To achieve this, use a new @for loop in ...

Utilizing AES encryption in C# and decrypting it in Angular, converting it from a byte[] / number array with the help

I am looking to securely encrypt and decrypt a byte[] in a C# API endpoint, then convert the decrypted document to base64 for viewing in a PDF viewer within an Angular 14 app. I came across this helpful guide on Stack Overflow [https://stackoverflow.com/q ...

Step-by-step guide on developing an AngularJs provider using TypeScript

As I've developed a Directive that incorporates various Css classes, it would greatly enhance its flexibility if the Css classes could be configured at Application start within the config section. I believe utilizing a provider is the appropriate appr ...

Automated tools and frameworks for the testing of website performance

Hello, I have a website that heavily relies on AJAX for server communication. I am looking to conduct performance and stress testing using automated scripts. Can you provide any suggestions or recommendations? I am specifically interested in the functiona ...

developing a seamless and uncomplicated banner text animation

Greetings everyone! I am diving into the world of JavaScript and recently attempted to create a banner carousel animation. Specifically, I have 3 banners in rotation where each slide reveals text with an animation effect. However, I'm encountering an ...

Creating a plug-in enables you to discover and journey through geographical information on a three-dimensional globe using a web browser

Recently, I completed a mini project utilizing the three.js library. Now, I am looking to develop a Javascript plugin that can efficiently load large 3D models and utilize a Javascript API on the client side similar to Google Earth Plugin for faster perfor ...

Guide on setting up a React project using a customized version of create-react-app

Is there a way to specify the version of create-react-app when creating a new React application? I want to use version 1.0.10 specifically, but when I run create-react-app myProject, it always defaults to the latest version available at that time. ...

generate a new .json file using Node.js

My current task involves creating a .json file using JS and nodejs to store data from MongoDB. However, whenever I execute my function, an error pops up in the console: Uncaught TypeError: Cannot read property 'prototype' of undefined. After ...

struggling with responseText functionality in javascript

I am encountering an issue with passing variables from PHP to JavaScript using JSON. The problem lies in the fact that I am able to debug and view the items in the responseText within my JavaScript, but I am unable to assign them to a variable or properly ...

What could be causing the custom Angular filter to not return the expected results?

I have been working on a custom filter called "occursToday" for an array of "event" objects. This filter is supposed to return events that have a startDate matching the current date. However, when I test the filter, no events are displayed despite expectin ...

Chrome hanging after AJAX delete operation has been executed

After conducting a same-origin AJAX delete using jQuery, any subsequent calls made by the same client to the server are getting stuck. The specific issue is outlined below. Can you please review and let me know if there's something incorrect, as this ...

What is the best way to adjust the size of an image to the viewing area

In my application, users can take photos either horizontally or vertically. These images are then displayed in a gallery on a webpage, and when clicked on, they expand using a Modal. My issue arises with horizontal images looking smaller than vertical one ...

Accessing the internal undo and redo feature of a textarea input

Regular text areas and editable iframes come with a built-in undo/redo feature. However, when inserting certain content, this action cannot be undone because it does not register in the undo buffer. Is there a method to add custom states to the undo/redo ...