Reputation: 1098
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="["one","two","thee"]">
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
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="["one","two","thee"]" >
<div id="app">
<ul>
<li v-for="word in words">{{word}}</li>
</ul>
</div>
Upvotes: 2