Reputation:
I'm trying to figure out a way to check the DOM for a specific element with a class name of 'amp'. If this matches then I want a new Vue instance to be created and use the data attributes in the HTML to be used as data(). I'm guessing some sort of loop would be needed?
Is this possible and what would be the right approach?
Thank you.
HTML example:
<div class="amp" id="vue" data-contentDeliveryUrl="www.urlexample.com" data-encodedQuery="=query234" data-cidItem="555-555-555"></div>
<div class="amp" id="vue" data-contentDeliveryUrl="www.urlexample.com" data-encodedQuery="=query123" data-cidItem="666-666-666"></div>
index.js
Example of a new instance
new Vue({
el: '#vue',
data() {
return {
contentDeliveryUrl: contentDeliveryUrl,
encodedQuery: encodedQuery,
cidItem: cidItem
}
},
render: h => h(Page)
})
Upvotes: 1
Views: 327
Reputation: 26731
You could use document.querySelectorAll
to return a NodeList of elements that contain the amp
class. Then, iterate over that list to create Vue instances.
To set the Vue data properties you would need to use the spread operator along with el.dataset
. The data attributes in your HTML need to be separated with a hyphen instead of using camelcase.
(function() {
document.querySelectorAll('.amp').forEach(el => {
new Vue({
el,
data() {
return {
...el.dataset,
}
},
mounted() {
console.log(this.$data)
// this.contentDeliveryUrl
// this.encodedQuery
// this.cidItem
},
})
})
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="amp" id="vue" data-content-delivery-url="www.urlexample.com" data-encoded-query="=query234" data-cid-item="555-555-555"></div>
<div class="amp" id="vue" data-content-delivery-url="www.urlexample.com" data-encoded-query="=query123" data-cid-item="666-666-666"></div>
Upvotes: 3