首页 > 解决方案 > vue在一个组件中打开一个组件

问题描述

在 App.vue 我有一个按钮来打开一个组件。在组件 BigForm 中,我还有一个按钮可以打开一个名为 的组件。但是当我打开组件时。Vue 重新渲染带有警告的页面:

The "data" option should be a function that returns a per-instance value in component definitions.

应用程序.Vue

 <template>
  <div id="app">
    <button @click="showModal()">Show</button>
    <BigForm v-if="modal" />
  </div>
</template>
<script>
import BigForm from "./components/BigForm";
export default {
  name: "App",
  components: {
    BigForm,
  },
  data() {
    return {
      modal: false,
    };
  },
  methods: {
    showModal() {
      this.modal = !this.modal;
    },
  },
};
</script>

BigForm.vue:

<template>
  <div class="hello">
    <form style="height: 300px; width: 300px; background-color: green">
      <button @click="showSmallForm()">Show small form</button>
      <SmallForm
        v-if="toggleSmallForm"
        style="width: 100px; height: 100px; background-color: yellow"
      />
    </form>
  </div>
</template>
<script>
import SmallForm from "./SmallForm";
export default {
  name: "HelloWorld",
  components: {
    SmallForm,
  },
  data() {
    return {
      toggleSmallForm: false,
    };
  },
  methods: {
    showSmallForm() {
      this.toggleSmallForm = !this.toggleSmallForm;
    },
  },
};
</script>

和 SmallForm.vue:

<template>
  <form>
    <input placeholder="Small form input" />
    <button>This is small form</button>
  </form>
</template>

这是我在代码框中的示例的代码:

https://codesandbox.io/s/late-cdn-ssu7f?file=/src/App.vue

标签: vue.jsvuejs2vue-component

解决方案


问题与 Vue 本身无关,而与 HTML 有关。

当您使用<button>inside<form>时,该按钮的默认type值为submit选中此项) - 当您单击该按钮时,表单将提交给服务器,从而导致页面重新加载。

您可以通过显式设置类型<button type="button">(HTML 方式)或阻止默认操作(Vue 方式)来防止这种情况<button @click.prevent="showSmallForm()">Show small form</button>(请参阅事件修饰符

另请注意,在 HTML中不允许<form>使用in another<form>


推荐阅读