Vue Prop Sync on multiple levels (TypeScript & JavaScript & ClassStyle)

1.9k views Asked by At

I just started programming with Vue and ts/js so please forgive me if I miss something obvious :)

I am trying to pass a prop down two levels. If level 3 modifies the prop it also changes on level 2 but not on level 1.

Level 1 is a component I wrote and it is written in ts.

<template>
 <Child :varr.sync="obj.attr" />
</template>

export default Parent class extends Vue { 
  obj: Object = {
    attr: [1, 2, 3]
  };
}

Level 2 is a component I wrote and it is written in ts.

<template>
 <ChildsChild :layout.sync="arr" />
</template>

export default Child class extends Vue { 
  @PropSync("varr", { type: Array }) arr!: number[];
}

Level 3 is a component I DID NOT write and it is written in js.

export default {
  props: {
      layout: {
                type: Array,
                required: true,
              }
         }
}
1

There are 1 answers

0
NickHilton On

When you pass something down to a child, you need to be careful to not update the prop directly on the child, because this is actually re-rendered every time the parent updates.

In your case, I'm not really sure why the PropSync isn't working. The similar pattern I've seen before is separating out the prop and adding a watcher as below

i.e. Parent

<template>
 <Child :varr.sync="obj.attr" />
</template>

export default Parent class extends Vue { 
  obj: Object = {
    attr: [1, 2, 3]
  };
}

Child:

<template>
 <ChildsChild :layout.sync="passed_varr" />
</template>

export default Child class extends Vue { 
 props {
  varr: {
   type: Object
  } 
 }
 data: instance => ({
  passed_varr: instance.varr,
 }
 watch: {
  passed_varr: {
   handler() {
    this.$emit('update:varr', this.passed_varr);
   },
   deep: true,
  },
 },
}

In this case, the prop varr is synced with the parent component, so when layout is updated in the grandchild, it syncs with child.passed_varr which has a watcher to emit an update to parent.varr

Looking at the docs here it seems like PropSync is doing a similar thing, so not sure on the particular differences