Home > Software design >  How to make statement with Vue and data from HTML
How to make statement with Vue and data from HTML

Time:02-15

how to take the data-id from HTML and add it to Vue?

<li data-id="01" >List 1<li>
<li data-id="02" >List 2<li>
<li data-id="03" >List 3<li>
mouseEvent() {
   if ( this.data-id === "01") {
   // do something
   }
},

CodePudding user response:

I don't quite understand your needs, However, you write it more like jQuery, In Vue, the typical way of writing is like this:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>

<body>
    <div id="app">
        <ol v-for="data in dataList" v-on:click="method1">
            {{ data.value }}
        </ol>
    </div>

    <script>
        var app = new Vue({
            el: '#app',
            data: {
                dataList: [
                    {value: "List 1",},
                    {value: "List 2",},
                    {value: "List 3",},
                ]
            },
            methods: {
                method1: function (e) {
                    // console.log(e);
                    console.log(e.target);
                }
            }
        })
    </script>
</body>

</html>

CodePudding user response:

You can access it via e.target.attributes['data-id'].nodeValue.

Working Demo :

const app = new Vue({
  el: '#app',
  data() {
    return {
      list: [{
        id: '01',
        name: 'List 1'
      }, {
        id: '02',
        name: 'List 2'
      }, {
        id: '03',
        name: 'List 3'
      }]
    }
  },
  methods: {
    mouseEvent(e) {
        console.log(e.target.attributes['data-id'].nodeValue);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.0/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="(item, index) in list" :key="item.id" :data-id="item.id" @mouseover="mouseEvent">
      {{item.name}}
    </li>
  </ul>
</div>

  • Related