dev404
dev404

Reputation: 1098

How do you set a Vue property to the value of a stringified element attribute?

Forgive me for the very silly question.

I have something like this:

var app = new Vue({
  el: '#app',
  data: {
    words: []
  },
  created() {
    let something = document.getElementById('word_data')
    if (something) { this.words = something.dataset.content.slice() }
  }
})

And this is the HTML part:

<input type="hidden" id="word_data" data-content="[&quot;one&quot;,&quot;two&quot;,&quot;thee&quot;]">

which is just an array in the format of ["one", "two", "three", "four", "etc"].

I'm trying to assign this array to words in Vue. How can I do this?

If I assign it as it is in my example, it will take the whole array as a single record.

I'm sure it's something very simple. What am I missing?

Upvotes: 1

Views: 92

Answers (1)

msanford
msanford

Reputation: 12229

Just get the element's data-content attribute value, then use JSON.parse() to convert it from the format you've provided.

var app = new Vue({
  el: '#app',
  data: {
    words: []
  },
  created() {
    const element = document.getElementById('word_data');
    const data = JSON.parse(element.getAttribute('data-content'));
    if (data) { this.words = data }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<input type="hidden" id="word_data" data-content="[&quot;one&quot;,&quot;two&quot;,&quot;thee&quot;]" >

<div id="app">
  <ul>
    <li v-for="word in words">{{word}}</li>
  </ul>
</div>

Upvotes: 2

Related Questions