Categories
Vue Answers

How to Pass Props as Initial Data in Vue.js?

Spread the love

Sometimes, we want to pass props as initial data in Vue.js.

In this article, we’ll look at how to pass props as initial data in Vue.js.

Pass Props as Initial Data in Vue.js

We can pass props as initial data in Vue.js by setting the initial value of a reactive property to the prop’s value.

For instance, we can write:

App.vue

<template>
  <div id="app">
    <HelloWorld msg="world" />
  </div>
</template>

<script>
import HelloWorld from "@/components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld,
  },
};
</script>

HelloWorld.vue

<template>
  <div class="hello">
    <h1>hello {{ message }}</h1>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      message: this.msg,
    };
  },
};
</script>

In HelloWorld , we set message to this.msg as message ‘s initial value.

We make a copy of the this.msg string and set it as message ‘s value.

If it’s not a primitive value, then we’ve to make a copy of the prop’s value with Object.assign or the spread operator.

Conclusion

We can pass props as initial data in Vue.js by setting the initial value of a reactive property to the prop’s value.

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 *