Skip to content

Instantly share code, notes, and snippets.

@pbowyer
Created April 28, 2023 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbowyer/83ca163b840987cfa2da42b81a4daf80 to your computer and use it in GitHub Desktop.
Save pbowyer/83ca163b840987cfa2da42b81a4daf80 to your computer and use it in GitHub Desktop.
Loading data attributes into a Vue 3 app
import {createApp} from 'vue';
import {processDataAttributes} from "../lib/process-data-attributes.js";
const app = createApp({
data() {
return {
rootData: processDataAttributes(document.getElementById("app"))
}
}
});
app.mount('#app');
// Taken from jQuery source code
const processDataAttribute = function ( data ) {
if ( data === "true" ) {
return true;
}
if ( data === "false" ) {
return false;
}
if ( data === "null" ) {
return null;
}
// Only convert to a number if it doesn't change the string
if ( data === +data + "" ) {
return +data;
}
if ( /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/.test( data ) ) {
return JSON.parse( data );
}
return data;
}
export const processDataAttributes = function ( domElement ) {
const rootData = {};
Object.entries(domElement.dataset).forEach(([key, value]) => {
rootData[key] = processDataAttribute(value);
});
return rootData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment