What is the best way to assign a Vue property the value of a stringified element attribute?

Apologies for the question that may seem silly.

Here is the code snippet I am currently working with:

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

Now, here is the HTML section:

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

This HTML section represents an array in the format of

["one", "two", "three", "four", "etc"]
.

I am attempting to assign this array to the words variable in Vue. How can I accomplish this?

If I simply assign it as shown in my example, it treats the whole array as a single record.

I am certain the solution is straightforward. Can you point out what I might be overlooking?

Answer №1

To extract the value of the element's data-content attribute, simply retrieve it and then utilize JSON.parse() to convert it into the provided format.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS: Initiate a Bootstrap modal upon webpage loading

As I work on designing a web application using AngularJS, I aim to implement the launching of a bootstrap modal upon page load through AngularJS. Here is the structure of my modal: <div class="modal hide fade" id="myModal"> <div class="moda ...

Safari and iOS users may not experience the onended() event triggering

Code snippet performs as expected on Chrome 80.0 and Firefox 74.0 (OSX 10.14.6). However, when testing on OSX Safari 13.0.5 or iOS (using Chrome, Safari), the <div> element fails to turn blue, suggesting that the onended callback is not triggering. C ...

The parameter provided is neither a User nor a Role, resulting in a TypeError of INVALID_TYPE in Discord.js

After initially coding these functions, I encountered an unexpected behavior with .overwritePermissions() erasing set permissions. Upon revisiting my code to address this issue, I aimed to modify joinPrivateChannel() to utilize .updateOverwrite() in order ...

Error Encountered in MERN Stack Development: TypeError Thrown Due to Inability to Convert Undefined

Currently, I am following the MERN Stack, Front To Back Course by Traversy Media. I am in the process of setting up the login functionality for the application. Despite ensuring that my code matches his exactly, I am encountering an error: TypeError: Canno ...

Implement auto partial page refreshing in ASP.NET without using the UpdatePanel feature

Looking to implement auto partial page refresh in asp.net without sending excessive data through UpdatePanel. Considering using a webservice called by JavaScript instead, but unsure how to trigger it automatically rather than by button click event. Many e ...

Verifications in the realm of javascript

I created a custom form in Django which is functioning correctly. However, when I try to implement JavaScript validation, the validations do not seem to work as expected. I am looking to validate the form using JavaScript. Although it displays the alert me ...

What could be causing my React function to be declared but not utilized?

Struggling with my React project, I hit a roadblock when trying to import my generalInput file into my App file. The error message stated that the generalInput was declared but never read. Desperate for a solution, I even turned to AI for help, but it too ...

Regular expression: match all content up to a certain word(s)

I have two different versions of a string that look like this: The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115 Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 978128011 ...

How can the label value be updated in a material ui slider component?

code snippet: https://codesandbox.io/s/runtime-worker-kxse3?file=/src/App.js Can anyone help me ensure that the labels in the bubble display the same values as the text (3, 5, 7, 10)? ...

Is it impossible to modify an enumerable attribute within a JSON.stringify replacer function?

I'm having some trouble trying to serialize non-enumerable properties within the replacer function. Can someone point out what might be going wrong in this code snippet? Any help would be greatly appreciated. var obj = {x:1,y:2}; Object.definePrope ...

Encountered a parsing error when attempting to integrate SCSS with webpack and babel setup

I am facing an issue while trying to integrate SCSS into my webpack and babel setup. When running npm run build, I encounter an error that I'm unfamiliar with. As a beginner in using webpack and babel, I'm unsure about the necessary changes requ ...

Can a photo frame app be created using PhoneGap?

I'm looking to develop an application where I can capture a picture, crop the face of a person, and then embed this face into a frame. Is there a solution using PhoneGap for this task? Can anyone provide some ideas on how to get started? Thank you i ...

Transmit information to Vue.js component

I am encountering an issue while attempting to transfer data from one component to another. Can someone provide assistance? Below is the code snippet: <template> <div class="q-pa-md" style="max-width: 900px"> <div v-if="fields.length" ...

Is it possible to pass an additional parameter through the function called by the Array.forEach method?

I have created an array named allchildsAr and I am populating it with objects that contain a parent property (an object) and a chlds property which is an Array. Here is the code to fill the array : Ti.API.info("*****allchildsAr["+level+"] is null and "+e ...

What is the best way to selectively print the contents of a child window upon page load?

I've created a function that opens a child window and fills it with content using AJAX. function OpenWindow(){ jQuery.ajax({ type: 'POST', data: { //some fields }, url: 'getPageForPrint.php', su ...

Customizing a form with the choice to save or cancel changes

Just starting out with VueJS, I'm looking to create a form that includes basic Save and Cancel functionality. Currently, the model is tightly bound to the input fields so they update instantly as changes are made. However, I'd prefer to have more ...

I'm having trouble connecting my HTML code with my Vue component

Today marks my second day delving into the world of vue. Having experience with webpack and vue-cli beforehand, I am now eager to understand how to streamline everything within a single file. The goal is to refactor my current code in order to create a reu ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

"Exploring the ThreeJS library's ability to rotate objects within

I have a collection of individual objects in an Array that I want to rotate as a single object. Here is an example: //retrieve body parts from the console bodyParts //Result [THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.M ...

Using GraphQL to set default values in data within a useEffect hook can lead to never

Here's the code snippet that I'm working with: const [localState, setLocalState] = useState<StateType[]>([]); const { data = { attribute: [] }, loading } = useQuery<DataType>(QUERY, { variables: { id: client && client.id ...