0

Take the following example code:

new Vue({
  el: '#app',
  data: {
    name: 'Test'
  },
  computed: {
    hover: function () {
        //I'd like to use the "data-prefix" here instead of "XXX"
        return this.name + "XXX"; 
    }  
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <select>
    <option data-prefix="ABC" v-bind:title="hover">1</option>
    <option data-prefix="XXX" v-bind:title="hover">2</option>
    <option data-prefix="YYY" v-bind:title="hover">3</option>
  </select>
  
  <input type="text" name="name" v-model="name">
</div>

Here I have a legacy application that generates a select with varios options in it. I've modified the legacy app to put all information I need into "data-" attributes(plus add "v-bind").

Now I'd like to use this information in various ways in my Vue control, in this particular example I'd like to use the "data-prefix" in the title attribute on each option in my selection.

However I don't know how to access that property from the computed property. Is there a way to do this with Vue?

I've look at the documentation for this, and I don't see this noted anywhere. Has this been done anywhere else?

tony19
  • 125,647
  • 18
  • 229
  • 307
David Rogers
  • 2,601
  • 4
  • 39
  • 84
  • You have to access the Dom to get the value of attribute= **data-prefix**, so uses **ref** or **custom-directive** will be one solution. But better solution will be re-design your app whch uses data-driven pattern instead. – Sphinx Oct 11 '18 at 19:35
  • Normally you will bind an object containing all informations needed, the binding goes to the select element and the options get objects as values – mech Oct 11 '18 at 21:00

1 Answers1

0

As mentioned in the comments you will actually need to rethink how your data can be set to the component data or property. Then use it directly from it rather than binding your data to your DOM attribute and accessing it from DOM.

For instance in your example mentioned above for showing the hover you actually do not need the data-prefix DOM attribute. It can be set to an array in the data. Then from the array set to the title to show your hover. Like this:

new Vue({
  el: '#app',
  data: {
    prefix:[{id:1, name:'ABC'}, {id:2, name:'XXX'}, {id:3, name:'YYY'}],
    name: 'Test'
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <select>
    <option v-for="obj in prefix" :title="name+obj.name">{{obj.id}}</option>
  </select>
  
  <input type="text" name="name" v-model="name">
</div>
zapping
  • 4,118
  • 6
  • 38
  • 56