Lorenzo Andreasi
Lorenzo Andreasi

Reputation: 333

Vue3: problems with v-model, it does not update the component

I have this code here, it basically fetch from firestore in the setup(), then display the information with the Categoria component. It also should update the Categoria components when the <span> is pressed. However, something don't work. My snippet successfully update the database but does not reload the component... any ideas?

<template>
  <div class="header">
    <span class="mdi mdi-home icona" />
    <h1>Modifica menù</h1>
  </div>
  <Categoria
    v-model="categorie"
    v-for="categoria in categorie"
    v-bind:key="categoria"
    :Nome="categoria.nome"
  />
  <div class="contenitore_aggiungi">
    <span @click="crea()" class="mdi mdi-plus aggiungi" />
  </div>
</template>

<script>
import Categoria from "@/components/edit/Categoria-edit.vue";
import { useRoute } from "vue-router";
import { creaCategoria, ottieniCategorie } from "@/firebase";

export default {
  name: "Modifica",
  components: { Categoria },
  async setup() {
    const route = useRoute();
    let idRistorante = route.params.id;
    let categorie = await ottieniCategorie(idRistorante);
    console.log(categorie);
    return { idRistorante, categorie };
  },
  methods: {
    crea() {
      let nuovaCategoria = "Nuova categoria";
      creaCategoria(this.idRistorante, nuovaCategoria);
      this.categorie.push({ nome: nuovaCategoria });
      console.log(this.categorie);
    },
  },
};
</script>

Thanks for your answers!

Upvotes: 0

Views: 997

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50890

You need to declare categorie as a reactive property. Also you can write methods in setup() itself instead of methods:

import { ref } from 'vue'

export default {
  setup() {
    const route = useRoute();
    let idRistorante = route.params.id;
    const categorie = ref({}) // <-- add default value of properties

    const getData = async () => {
        const data = await ottieniCategorie(idRistorante);
        categorie.value = data
    }

    getData() // or void getData() 

    const crea = () => {
      let nuovaCategoria = "Nuova categoria";
      categorie.value.push({ nome: nuovaCategoria });
      console.log(categorie.value);
    },

    return { idRistorante, categorie, crea };
  }
}

Make sure the default value of categorie is set in ref(). If it's an array set it to ref([]).

Upvotes: 1

Related Questions