[Vuejs]-Vue 3 watched property does not update

-1๐Ÿ‘

I built a couple of test components in my Vue 2 CLI sandbox application, but hopefully it will translate enough to Vue 3 to help you solve your problem. Also, not sure if it is contributing to your problem, but you may want to take a look at this Event Names documentation.

Parent.vue

<template>
  <div class="parent">
    <h3>Parent.vue</h3>
    <hr>
    <child :formState="formState" @form-state-event="updateFormState" />
  </div>
</template>

<script>
  import Child from './Child.vue'

  export default {
    components: {
      Child
    },
    data() {
      return {
        formState: 'Initial State'
      }
    },
    methods: {
      updateFormState(newState) {
        console.log('updateFormState');
        this.formState = newState;
      }
    }
    
  }
</script>

Child.vue

<template>
  <div class="child">
    <h3>Child.vue</h3>
    <div class="row">
      <div class="col-md-6">
        <label>Form State From Parent (Prop):</label>
        <span>{{ dataFormState }}</span>
      </div>
    </div>
    <div class="row">
      <div class="col-md-6">
        <button type="button" class="btn btn-sm btn-secondary" @click="changeAndEmit">Emit new form state</button>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      formState: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        dataFormState: this.formState,
        clickCounter: 1
      }
    },
    watch: {
      formState(newValue) {
        this.dataFormState = newValue;
      }
    },
    methods: {
      changeAndEmit() {
        console.log('Emitting values up')
        this.$emit("form-state-event", "New form state " + this.clickCounter++);
      }
    },
  }
</script>

<style scoped>
  label {
    font-weight: bold;
    margin-right: 0.5rem;
  }
</style>
๐Ÿ‘คTim

Leave a comment