【问题标题】:Vue3: problems with v-model, it does not update the componentVue3:v-model的问题,它不更新组件
【发布时间】:2021-11-09 16:50:35
【问题描述】:

我这里有这段代码, 它基本上从setup() 中的firestore 中获取,然后使用Categoria 组件显示信息。它还应该在按下<span> 时更新Categoria 组件。但是,有些东西不起作用。我的 sn-p 成功更新了数据库,但没有重新加载组件……有什么想法吗?

<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>

感谢您的回答!

【问题讨论】:

    标签: javascript firebase vuejs3


    【解决方案1】:

    您需要将categorie 声明为reactive property。您也可以在setup() 本身而不是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 };
      }
    }
    

    确保categorie 的默认值设置在ref() 中。如果是数组,则设置为ref([])

    【讨论】:

    • 成功了!我现在不能在 setup() 中编写方法,这将非常有用!
    猜你喜欢
    • 1970-01-01
    • 2021-02-21
    • 2018-06-26
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2019-02-14
    • 2022-06-28
    相关资源
    最近更新 更多