How to pass props as initial data in Vue.js 2?

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

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

How to pass props as initial data in Vue.js 2?

To pass props as initial data in Vue.js 2, we can return the value of the prop in the data method.

For instance, we write

<script>
export default {
  //...
  props: ["initialCounter"],
  data() {
    return {
      counter: this.initialCounter,
    };
  },
};
</script>

to set the initial value of the counter reactive property to the initial value of the this.initialCounter prop.

We register the prop with

props: ["initialCounter"]

Conclusion

To pass props as initial data in Vue.js 2, we can return the value of the prop in the data method.