简体   繁体   中英

Vue open a component in a component

In App.vue I have a button to open a component . Inside the component BigForm, I also have a button to open a component named, . But as I open the component. Vue re-render the page with the warning:

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

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

And SmallForm.vue:

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

This is the code to my example in codesandbox:

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

The problem is not related to Vue itself but the HTML.

When you use <button> inside <form> , the default type of the button is submit ( check this ) - when you click the button, the form is submitted to the server causing the page to reload.

You can prevent that by explicitly setting type <button type="button"> (HTML way) or by preventing default action (Vue way) <button @click.prevent="showSmallForm()">Show small form</button> (see event modifiers )

Also note that using <form> in another <form> is not allowed in HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM