Vue: Update a sync property inside a method

196 views Asked by At

I'm trying to use sync property pattern so that I can share a unique property between parent and child (so using a pattern like vuex seems unnecessary to me, like throwing a bomb at a fly). I have managed to connect synchronous properties as follows:

Child:

<template>
    <v-btn @click="syncedProp = false"> Done </v-btn>
</template>

export default {
  props: {
    myProp: {
      type: Boolean,
    },
  },
  computed: {
    syncedProp: {
      get() {
        return this.myProp
      },
      set(value) {
        this.$emit('update:myProp', value)
      },
    },
  },
}

Parent:

<template>
    <Child :myProp.sync="parentProp"/>
</template>

export default { 
  data: function(){
    return {
       parentProp = ''
    }
  }
}

This strategy has worked for me, it does what is expected of emitting the event of modifying the property from the child so that the parent updates it and the change is reflected in the child. But my problem is that now the intention of the child to modify the property I want to do from a method and not directly. This means (look @click line):

Child with method:

<template>
  <v-btn @click="changeProperty(false)"> Done </v-btn>
</template>

export default {
  props: {
    myProp: {
      type: Boolean,
    },
  },
  computed: {
    syncedProp: {
      get() {
        return this.myProp
      },
      set(value) {
        this.$emit('update:myProp', value)
      },
    },
  },
  methods: {
    changeProperty(value) {
      this.syncedProp = value
    }
  }
}

As you can see from the button I call the method that updates the property, which should call the $emit. But with the method it doesn't but without the direct method it does. Why is this? How could I do it with the method? Thanks.

0

There are 0 answers