Vue Answers

How to pass props to Vue root instance via attributes on element the app is mounted on?

Spread the love

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">
  <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=""></script>
  <div id="app" app-title="Hello from Parent"></div>

    // 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>'

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *