How To Pass Data Between Components In Vue.js

How to pass data in one component to another component in VueJS. In this article we are going to learn “How To Pass Data Between Components In Vue.js. This is the basic way to pass data between component in Vue JS.

First of all you need to know the basic knowledge of Vue JS. So lets’ start then.

In my project, I have,

  • UserInput.vue
  • Home.vue
  • ListView.vue

UserInput.vue and ListView.vue files are the components.


01. UserInput.vue Component implementation

This is the component that is to pass data. Lets see how this works.

<template>
  <div class="hello">
    <input
      placeholder="Enter Text Here"
      v-model="tempMessage"
      @keyup.enter="submit"
    />
    <br/>
  </div>
</template>

<script>
export default {
  name: "UsrMsg",
  data() {
    return {
      tempMessage: ""
    };
  },
  methods: {
    submit: function() {
      this.$emit("inputData", this.tempMessage);
      this.tempMessage = "";
    }
  }
};
</script>

02. ListView.vue Component Implementation

This is the component to get the passed data from the other component.

<template>
  <div>
    <li v-for="(message, index) in messageList" :item="message" :key="index">
      {{ message }}
    </li>
  </div>
</template>

<script>
export default {
  name: "Results",
  props: {
    msg: {
      type: String
    }
  },
  data: function() {
    return {
      messageList: []
    };
  },
  watch: {
    msg: function() {
      this.messageList.push(this.msg);
    }
  }
};
</script>

03. Home.vue implementation
<template>
  <div id="app">
    <UserInput @inputData="updateMessage" /> 
    <ListView :msg="childData" />
  </div>
</template>

<script>
import UsrMsg from "./components/UserInput";
import Results from "./components/ListView";

export default {
  name: "App",
  components: {
    UserInput,
    ListView
  },
  data: function() {
    return {
      childData: ""
    };
  },
  methods: {
    updateMessage(variable) {
      this.childData = variable;
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

For more details please visit – https://codesandbox.io/s/component-data-sharing-example-forked-0ox2l?file=/src/App.vue:0-683

This is the end of “How To Pass Data Between Components In Vue.js” article. Thank you for reading. If you are interesting on my article, make sure to follow my other articles as well. Make sure to leave a comment.

guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x