Vue.js - How to pass non-reactive data to child components

Viewed 2794

I know we can pass data to child components via Props. But it is reactive in one-way data flow mode. If the value of the data is changed in Parent component, it also has effect (update) on props in Child component.

In my case, I don't want to get update on specific prop in Child component even if that data in the Parent component is changed. It is because Child component will only responsible to show the data. But the data in the Parent Component still has to be reactive in Parent Scope.

I've read some forum article that suggest to use like Json. I feel it is a little dirty way and the data in my case is just one string.

Is there anyways to achieve that kind of solution?

3 Answers

You could copy the reactive prop in the created hook of the child component. The copy would not be reactive e.g.

export default {
  props: {
    reactive: Object
  },
  data: () => ({
    nonreactive: null
  }),
  created() {
    this.nonreactive = Object.assign({}, this.reactive)
  }
}

Note: the way you copy the reactive prop will depend on the data type, the way I've shown will work for objects.

Use prop as data property in child component. please see the fiddle link:

link here

Vue.component('greeting', {
  props: ['user'],
  data:function(){
    return {
      newuser:this.user
    }
  },
  template: '<h1>hi {{ newuser }}</h1>'
});
Related