composition 中声明的变量如何用于动态渲染?

How can a variable declared in composition be used for dynamic rendering?

我想要一个使用组合的 vue js v3 项目api,我已经声明了一个这样的变量

setup() {
    const showInvoiceItemForm = true;

    return { showInvoiceItemForm };
  },

现在我想在单击按钮并调用函数时显示一个表单

<form @submit.prevent="submit">
    <InvoiceItem
    :form="form"
    v-if="this.showInvoiceItemForm"
    ></InvoiceItem>

    <div class="mt-20 flex flex-row justify-between space-x-8">
        <BreezeButton type="button" @click="addInvoiceItem"
            >Add Item</BreezeButton
        >
        <BreezeButton>Generate Invoice</BreezeButton>
    </div>
</form>

方法是这样的

addInvoiceItem() {
    this.showInvoiceItemForm = true;
    console.log(this.showInvoiceItemForm);
},

在控制台中,我可以看到 showInvoiceItemForm 的值设置为 true,但从未显示该表单。看起来这个值从未真正改变过,那么使用组合 api 变量的正确方法是什么。

Vue 3 Composition API

setup() itself does not have access to the component instance - this will have a value of undefined inside setup(). You can access Composition-API-exposed values from Options API, but not the other way around.

您不必使用 this。查看将 v-if="this.showInvoiceItemForm" 更改为 v-if="showInvoiceItemForm" 是否有效,设置时也是如此。

尝试 this code snippet 看看是否有帮助。

您可以尝试使您的变量与 refreactive 反应并将所有移动到设置函数:

const { ref } = Vue
const app = Vue.createApp({
  el: "#demo",
  setup() {
    const showInvoiceItemForm = ref(false);
    const addInvoiceItem = () => {
      showInvoiceItemForm.value = true;
      console.log(showInvoiceItemForm.value);
    }
    return { showInvoiceItemForm, addInvoiceItem };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <form @submit.prevent="submit">
    <input v-if="showInvoiceItemForm" />
    <div class="mt-20 flex flex-row justify-between space-x-8">
      <button type="button" @click="addInvoiceItem"
        >Add Item</button>
      <button>Generate Invoice</button>
    </div>
  </form>
</div>

如果我理解正确,(点击按钮时需要显示表单),那么我希望这个解决方案对您有所帮助。

<template>
  <form @submit.prevent>
    <form v-if="showInvoiceItemForm">
      <input type="text" placeholder="Type text here">
    </form>

    <div>
      <button @click="addInvoiceItem">Add Item</button>
      <button>Generate Invoice</button>
    </div>
  </form>
</template>

<script>
import { ref } from 'vue';

export default {
  setup () {

    let showInvoiceItemForm = ref(false);

    function addInvoiceItem() {
      showInvoiceItemForm.value = !showInvoiceItemForm.value;
      console.log(showInvoiceItemForm.value);
    };
    
    return {showInvoiceItemForm, addInvoiceItem}
  }
}
</script>

此外,如果您不确定“值更改”,您可以安装 vue.js devtools,它非常有用。