main js pass data to vue

How to Pass Data from Main JS to Vue

Passing data is an essential part of building dynamic applications. In Vue.js, we can pass data from the main JS file to Vue components in various ways.

1. Props

The most common way to pass data from main JS to Vue is through props. Props are custom attributes that we can register on our components. We can pass data to props from the main JS file, and it will be available to the component.

<div id="app">
  <my-component v-bind:prop-name="dataFromMainJS"></my-component>

<script src="main.js"></script>

In the example above, we are passing data from the main JS file to the prop-name prop of the my-component component using the v-bind directive.

// main.js
new Vue({
  el: '#app',
  data: {
    dataFromMainJS: 'Hello, World!'

In the example above, we are defining a new Vue instance and passing the dataFromMainJS property with a value of 'Hello, World!'

2. Event Bus

We can also use an event bus to pass data from the main JS file to Vue components. An event bus is a Vue instance that we can use as a communication channel between components.

// main.js
let eventBus = new Vue();

// Emitting an event with data from main.js
eventBus.$emit('eventName', 'Data from main.js');

In the example above, we are creating a new Vue instance called eventBus. We are then emitting an event called eventName with data from the main JS file.

// my-component.vue
export default {
  created() {
    let self = this;
    // Listening to the event emitted in main.js
    eventBus.$on('eventName', function(data) {
      self.dataFromMainJS = data;
  data() {
    return {
      dataFromMainJS: ''

In the example above, we are listening to the eventName event in the created() lifecycle hook of the my-component component. When the event is triggered, we are setting the dataFromMainJS property to the data received from the event.


There are various ways to pass data from main JS to Vue components, including props and event buses. Choose the method that best suits your needs and build amazing applications!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]