Created
April 28, 2023 11:30
-
-
Save pbowyer/83ca163b840987cfa2da42b81a4daf80 to your computer and use it in GitHub Desktop.
Loading data attributes into a Vue 3 app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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