What is the best way to access data-* values in HTML 5 using Vue.js?

If I have the following HTML code:

<select class="form-control" name="gateway">
  <option data-type="typeA" value="1">Test String</option>
  <option data-type="typeB" value="2">Test String</option>
  <option data-type="typeC" value="3">Test String</option>
</select>
<span>@{{ typeMapper(data-type) }}</span>

And this Vue.js script:

const app = new Vue({
    el: '#vue-app',

    data: {},

    methods: {
        typeMapper: function (type) {
            var array = {
                'typeA':'You selected Type A',
                'typeB':'You selected Type B',
                'typeC':'You selected Type C',
            };
            return array[type];
        }
    }
});

How can we retrieve the data-type values in Vue.js?

The goal is to pass the selected option's data-type value to the Vue.js typeMapper method and display the result in the span tag.

We are unsure of how to achieve passing the data-type value to Vue.js!

For reference, we are using Vue.js 2.

Answer №1

Your data is not in a standard JavaScript array format, so I utilized the Object.keys function to extract the key names. Here is a simple solution to achieve your desired outcome:

<div id="app">
  <select class="form-control" name="gateway">
    <option v-for="(key,index) in Object.keys(array)" :value="index+1" :data-type="key">
      {{ array[key]}}
    </option>
  </select>
</div>

Below is the Vue code for implementation:

new Vue({
  el: '#app',
  data: {
    array: {
      'typeA': 'You selected Type A',
      'typeB': 'You selected Type B',
      'typeC': 'You selected Type C',
    }
  }
});

You can view a live example on this JSFiddle link.

Answer №2

It's puzzling why someone would want to extract data sets from a specific html5 structure. Typically, this can be achieved through ajax calls or by configuring select options using a different component.

However, if you do need to retrieve elements from an html structure, you can follow this example.

Check out the code here

HTML

    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>
    <div id="vue-app">
      <select class="form-control" v-on:change="typeMapper">
      <option data-type="" value="">Select Type</option>
      <option data-type="typeA" value="1">typeA</option>
      <option data-type="typeB" value="2">typeB</option>
      <option data-type="typeC" value="3">typeC</option>
    </select>
    <span>{{ gateway }}</span>
    </div>

JS

const app = new Vue({
    el: '#vue-app',
    data: {
      gateway: "",
    },
    methods: {
        typeMapper: function (event) {
          this.gateway = event.target[event.target.value].dataset.type;
        }
    }
});

This method is not the most efficient or compatible across various browsers. It might be advisable to consider alternative approaches instead.

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

issue arising from unique style identifiers in FireFox while making changes to styles via document.styleSheets

While experimenting with altering some stylesheets using JavaScript, I encountered an interesting issue: When attempting to set an attribute on a style rule in Firefox and the property is one of their proprietary ones, it fails silently. To demonstrate th ...

How to determine button placement based on the content present on the page

I'm struggling to find the right CSS positioning for a button on my page. I want the button to stay fixed in a specific location, but when there's a lot of content on the page, I need it to adjust its position accordingly. Initially, I want the ...

Step-by-step guide on dynamically fetching additional images from a directory using php, jquery, and ajax

I have a scenario where I have multiple folders, each containing up to 20 images. On my HTML page, I want to display the first 5 images and provide a "click to view more" option to show the remaining 15 images when clicked. Currently, the issue I am facin ...

What is the best way to resize my hamburger menu and achieve a flawlessly circular border for it?

I've been struggling to reduce the size of my hamburger menu (both height and width) for some time now. I managed to make it a bit smaller, but I can't seem to figure out how to shrink it further. Additionally, I'm having trouble creating a ...

Scroll to the top of jQuery DataTables when clicking pages in a random order from the bottom to the top and

In my current project, I am working with jQuery Datatables and I need to customize its default behavior. Currently, when I navigate to page 61, the page scroll remains at the bottom of the page. However, if I then click on a lower page number like 60, th ...

Split the outcome and its handling into individual files

My script requires me to make an XML request, receive the response from the server (if resolved), parse it, and store the parsed result in a variable. Only after this process can I proceed with various tasks. To achieve this separation of concerns, I aim ...

In search of an effortless method to effortlessly select numerous elements using a handy bookmarklet

My goal is to develop a bookmarklet that can perform various functions on different webpages with ease. The concept involves placing it in a convenient location, such as the bookmark bar, and executing a "standard function" on a particular page. Instead of ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...

What is the process for embedding MUI into a React Integrated Astro platform?

As I delve into learning Astro, my idea is to incorporate MUI's material components like Button and Typography within the Astro components since I have already enabled React integration. astro.config.js import { defineConfig } from 'astro/config ...

Using the scrollIntoView() method in VUE.js to center an li element within a component

One of the components I'm working with has multiple list items, and I want to achieve a functionality where clicking on any item will center it inside the component, making it visible in the center of the view. <card-maintenance v-for="m ...

Javascript error specific to Internet Explorer. Can't retrieve the value of the property 'childNodes'

After removing the header information from the XML file, the issue was resolved. Internet Explorer did not handle it well but Firefox and Chrome worked fine. An error occurred when trying to sort nodes in IE: SCRIPT5007: Unable to get value of the proper ...

Scroll to the bottom with jQuery Chat feature

Is there a way to check if a user is at the bottom of a messages div when new messages are added? Currently, my script automatically scrolls to the bottom when the chat is loaded or a new message is sent. However, I don't want it to scroll to the bott ...

Getting the value of a selected ExtJS combobox using selenium: A step-by-step guide

Currently, I am facing a situation where my webpage is being rendered using ExtJS. It renders multiple Comboboxes each with a unique generated ID and a different option selected in each one. I want to be able to determine which value is selected in each co ...

What is the best way to quickly search for div results?

I've managed to display results in a table format, creating a grid layout by using td tags for each element. However, when I tried to filter the results based on text inputted into a textbox using JS code, only the labels are showing up. What I reall ...

Uh-oh, Ajax encountered a 500 Internal Server Error!

Utilizing ajax to fetch events from my database has hit a snag. Instead of displaying the results, there is nothing visible on the screen, and the console is showing this error message: POST http://www.example.com/system/live_filter.php 500 (Internal Se ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here The project involves two lists - one containing pets and the other ...

What is the best way to convert a recordset to an array using React?

I'm attempting to create an array by retrieving data from a SQL recordset: +------------+------------+------------+ | start_type | field_name | start_text | +------------+------------+------------+ | 0 | Field1 | some text. | +----------- ...

Vue.js running locally does not trigger the ready function

When running the following code in jsfiddle, there are no issues. However, when attempting to run it on localhost, the ready function does not fire and the ordered list items are not displayed. How can this be resolved? index.html <body> <h3&g ...

Node.JS file upload fails to maintain the current state of uploaded files

I am encountering an issue with my Node.js server-side script where it successfully uploads a file to a specified directory, but it is not the intended file. The script throws an error message: Request received: POST undefined:1 ------WebKitFormBoundar ...