[Vue] Passing Data to Child via props and Fixing Dynamic Data with watch

Tech Sharing 2019-05-10
[Vue] Passing Data to Child via props and Fixing Dynamic Data with watch

Parent passes data via v-bind, child receives via props. But when the parent value is async (axios), the child won''t update — watching the prop fixes it.

Parent-child passing is clear in the Vue docs: the parent binds with v-bind, the child receives via props.

Parent binds data via v-bind:

<template>
  <router-view :yourdata="yourdata"></router-view>
</template>
<script>
export default {
  data: function() {
    return { yourdata: "A test string." }
  }
}
</script>

Child receives via props:

<template>
  <div>{{ yourdata }}</div>
</template>
<script>
export default {
  props: ['yourdata']
}
</script>

However, if the parent''s yourdata is dynamic (e.g. fetched async via axios), the child won''t update — use watch:

<template>
  <div>{{ newdata }}</div>
</template>
<script>
export default {
  data: function(){
    return { newdata: "" }
  },
  props: ['yourdata'],
  watch: {
    yourdata: function (newVal, oldVal) {
      this.newdata = newVal; // newVal is the new dynamic data, assigned to newdata
    }
  }
}
</script>