In Vue.js, you can pass props to the root Vue instance using HTML attributes on the element where the app is mounted.
This can be achieved using the propsData
option when creating the Vue instance.
To do this we write
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pass Props to Vue Root Instance</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="app" app-title="Hello from Parent"></div>
<script>
// Define the child component
Vue.component('child-component', {
template: '<div>{{ propFromParent }}</div>',
props: ['propFromParent']
});
// Create the Vue instance
new Vue({
el: '#app',
// Access attributes passed to the element where the app is mounted
propsData: {
// Access the attribute 'app-title' and pass its value as a prop to the root instance
titleProp: document.getElementById('app').getAttribute('app-title')
},
template: '<child-component :prop-from-parent="titleProp"></child-component>'
});
</script>
</body>
</html>
In this example, we have an HTML element with the ID app
, which is where our Vue app will be mounted.
We define a child component child-component
, which receives a prop called propFromParent
.
In the Vue instance, we use the propsData
option to pass props to the root instance.
We access the value of the app-title
attribute using document.getElementById('app').getAttribute('app-title')
.
We then use this value as a prop (titleProp
) in the template of the root instance, and pass it down to the child component as prop-from-parent
.
Now, the value of the app-title
attribute is passed as a prop to the child component.