简体   繁体   中英

How to get HTML 5 data-* values in Vue.js?

Assume I have this :

<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>

Here is my 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];
        }
    }
});

Now how can I get data-type values in Vue.js ?

I want to pass selected option data-type value to Vue.js typeMapper method and show the result in the span tag.

I don't know how to pass data-type value to Vue.js !

PS:

I'm using Vue.js 2

Your data isn't a true javascript array so I used the Object.keys function to grab the key names. Here's a quick way of doing what you're looking for:

<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>

And the Vue code:

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

Here's a working fiddle .

I have no clue as to why you'd want to gather data sets from a given html5 structure. Since you'd usually want to get that trough ajax calls or set the select options trough some other component or whatever.

If you however want to get the elements given from a html structure you'd do something like this.

codepen

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 is by far from optimal or a cross browser variant. If I were you I'd scrap this approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM