Switch image source to radio-selected option on Vue.js version 2

I am looking to update an image and trigger an image update.

Here is a demo example: http://jsbin.com/kuluyike/3/edit?html,js,output

  <div id="colorPicker">
    <img v-bind:src="color" :alt="color">
    <ul>
      <li v-for="c in colors">
        <label>
          <input type="radio" :id="c.name" name="color" v-model="color" :value="c.image">
          {{c.name}}
        </label>
      </li>
    </ul>
  </div>

  var cp = new Vue({
    el: '#colorPicker',

    data: {
      colors: [
        {
          name: 'red',
          image: 'red.jpg'
        },
        {
          name: 'pink',
          image: 'pink.jpg'
        },
        {
          name: 'blue',
          image: 'blue.jpg'
        }
      ],
      color: 'red.jpg'
    }
  });

However, this code does not work with Vue.js version 2.x.

How can I modify the code to make it compatible with version 2.x?

Answer №1

When using Vue 2.0, you will notice a change in syntax for attributes. Now, attributes need to be declared in the following way:

<img :src="color" :alt="color">
<input type="radio" :id="name" :name="color" v-model="color" :value="image">

A similar change applies to loops when using Vue 2.0, where v-repeat has been replaced with v-for:

<li v-for="(colorInfo, index) in colors">
<input type="radio" :id="colorInfo.name" name="color" v-model="color" :value="colorInfo.image">

In development mode with Vue 2.0, accessing an undeclared property will trigger a warning:

data: {
    // ...
    color: undefined,
},

var cp = new Vue({
    el: '#colorPicker',

    data: {
      color: undefined,
      colors: [
        {
          name: 'red',
          image: 'red.jpg'
        },
        {
          name: 'pink',
          image: 'pink.jpg'
        },
        {
          name: 'blue',
          image: 'blue.jpg'
        }
      ]
    }
  });
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="186e6d7d582a362d36292e">[email protected]</a>/dist/vue.js"></script>


<div id="colorPicker">
    <img :src="color" :alt="color">
    <ul>
      <li v-for="(colorInfo, index) in colors">
        <label>
          <input type="radio" :id="colorInfo.name" name="color" v-model="color" :value="colorInfo.image">
          {{colorInfo.name}}
        </label>
      </li>
    </ul>
  </div>

For more information, refer to: Migration from Vue 1.x - Vuejs

Answer №2

To loop in Vue 2.x using `v-for`, you can follow this example:

new Vue({
  el: '#colorPicker',
  data: {
    color: null,
    colors: [{
        name: 'red',
        image: 'red.jpg'
      },
      {
        name: 'pink',
        image: 'pink.jpg'
      },
      {
        name: 'blue',
        image: 'blue.jpg'
      }
    ]
  }
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4731322207756972697671">[email protected]</a>/dist/vue.js"></script>
<div id="colorPicker">
  <img :src="color" :alt="color" v-if="color" />
  <ul>
    <li v-for="c in colors">
      <label>
          <input type="radio" name="color" v-model="color" :value="c.image"/>
          {{c.name}}
        </label>
    </li>
  </ul>
  <p v-if="color"><b>Selected image name: </b> {{color}}</p>
</div>

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 select a specific button to handle the onSubmit event in a React form with multiple buttons

Imagine having the following HTML structure: <div id="container"></div> <p>Output: <span id="output"></span></p> accompanied by this block of JS code: function otherAction(e) { document.getElementById('output& ...

Delivering static assets through a POST request with express.js

I'm having an issue serving static content for a Facebook app using express.js app.configure(function (){ app.use('/', express.static(__dirname + '/public')); }); Everything is working fine with a GET request, but when I try ...

When a hard refresh is triggered, Vue's navigation guard takes precedence over localStorage

Currently, I am working on implementing a permission check for users before they can access a specific route. I have experimented with using both route.beforeEach and route.beforeResolve. Everything functions as expected if the localStorage within the tab ...

Tips for identifying the version of a package that is installed using a package-lock.json file containing lockfileVersion = 3

After upgrading from Node 16 (npm 8) to Node 18 (npm 9), I noticed a difference in the structure of the package-lock.json files. Files generated with npm 8 have a lockfileVersion: 2, while those generated with npm 9 have a lockfileVersion: 3. The changes a ...

Emails can be sent through a form without the need for refreshing

I am currently working on a webpage that utilizes parallax scrolling, and the contact box is located in the last section. However, I encountered an issue where using a simple HTML + PHP contact box would cause the page to refresh back to the first section ...

Processing one file to submit two forms to the database in Express

I am facing an issue with two forms on one form.hbs page using the same process.js file. Each form is processed by a different submit button for separate occasions. The first submit button works correctly, processing the data in the process.js file and se ...

Tips on calculating the combined value of price and quantity simultaneously

Greetings, kindly bear with me as my knowledge of JS scripting is quite limited. My expertise lies more in PHP programming. I stumbled upon this neat and straightforward script that calculates the total of product table rows and also provides the grand t ...

Guide to incorporating onchange event in a React.js project

Just starting out with reactjs and looking to incorporate onchange into my application. Utilizing the map function for data manipulation. handleChange = (event, k, i) => { this.setState({ dList: update(this.state.dList[k][i], { [ev ...

Discovering the properties of a class/object in a module with Node.js

Recently I delved into the world of node.js and found myself puzzled about how to discover the attributes, such as fields or properties, of a class or object from a module like url or http. Browsing through the official documentation, I noticed that it on ...

My email submission function is malfunctioning

my contact form in my website is not working properly. I have tried troubleshooting the issue by checking the contact.php file but it doesn't seem to be the problem. The script that I am using for the form submission is shown below: <!--Contact U ...

RadScheduler refresh rate

Currently I am incorporating RadScheduler into my project. The scheduler requires a regular update, so I have implemented a JavaScript function with an interval to call rebind() on the RadScheduler every 60 seconds. However, an issue arises when the user o ...

Combining Arrays in AngularJS: A Step-by-Step Guide

I have two arrays with dynamic values: $scope.objectName = [{ Name: '' }]; $scope.propertiesElement = [{ Key: '', Value: '' }]; How can I concatenate these arrays to achieve the following result? [{Name:''},{ Key: ...

Encountering a constructor problem while Jest is mocking a class from an NPM module

I'm currently attempting to create a mock for the Discord.JS module. Within this module, there is a Client class that I am extending in my own "Bot" class. My goal is to mock the module in order to simulate certain methods on other classes such as "Me ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Streamline event listeners with a pair of attributes

I am working with a function that requires one parameter: function magical(element){ ... } In my project, I have multiple click handlers attached to different elements and classes that are invoking this function: $('#div1').click(function(){ ...

Using Vue Js, I utilized Axios to make a call within a function, receiving and storing the retrieved data into an array

While working inside the function shown in the screenshot, I am encountering an issue when trying to access the data retrieved from the backend using axios.get. After exiting the axios block, the values of the array appear as undefined when I attempt to pr ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

Separate and add on the change validity status of an AngularJS form

If you want to test it out, check this jsFiddle link: HERE (it's recommended to view on a new jsFiddle, refer to the EDIT section of this post) I've noticed what seems like a bug in AngularJS or at least an unexpected behavior. When I detach a f ...

What is the best way to extract the information from the checkbox in a MUI datatable?

I am struggling to transfer an array with checked values to another table in order to display only those values. How can I achieve this? I am relatively new to using react and I find it challenging to grasp how some of the functions and components work. I ...

You cannot use objects as a React child. The object contains the keys {seconds, nanoseconds}

Currently, I am developing a React Calendar App that utilizes Firebase. I am encountering issues when trying to display the Date for each scheduled event. Below is my App code: import React, { useState, useEffect } from 'react' import firebase f ...