[英]Why function doesn't work with a button component but does with a button html tag in VUE js?
我做了一個VUE組件按鈕,並試圖關聯一個v-on:click函數,但是沒有用。 然后,我用HTML按鈕代替了它,然后它起作用了。 我需要明白為什么。
我做了這個按鈕組件,它的父組件加載正常
<template>
<button v-on:click="action">{{ name }}</button>
</template>
<script>
export default {
name: "Appbutton",
data: function() {
return {};
},
props: {
name: String,
}
};
</script>
代碼由其父級加載時沒有失敗:
<template>
<form class="login-form" action>
<label for="email">Register E-mail</label>
<input type="email" name="email" v-model="email" />
<label for="password">Register Password</label>
<input type="text" name="password" v-model="password" />
<div class="button-group">
<AppButton action="register" name="Login" />
<AppButton action="register" name="Login with Google" />
</div>
</form>
</template>
<script>
import AppButton from "@/components/AppButton";
export default {
name: "RegisterForm",
data() {
return {
email: "",
password: "",
show: true
};
},
methods: {
register: function(e) {
console.log("registered");
e.preventDefault();
}
},
components: {
AppButton
}
};
</script>
當按下“登錄”按鈕時,它在URL中重新加載了帶有參數email和password的頁面,但是console.log沒有顯示或在任何地方觸發。 我嘗試將“注冊”功能作為道具發送到AppButton.vue,但是它具有相同的行為。
僅當我將按鈕組件替換為常規HTML按鈕時,它才起作用。 現在它可以按預期工作了。
我只需要了解為什么這種行為,我該如何解決呢?
提前感謝。
不會因為表單submit
而發生。 將@submit.prevent
放在form
標簽上
<form class="login-form" action @submit.prevent>
<label for="email">Register E-mail</label>
<input type="email" name="email" v-model="email" />
<label for="password">Register Password</label>
<input type="text" name="password" v-model="password" />
<div class="button-group">
<AppButton action="register" name="Login" />
<AppButton action="register" name="Login with Google" />
</div>
</form>
首先,您必須將action
作為道具添加到AppButton中,然后您需要使用:click =“ register”綁定click事件。
我用示例制作了一個沙箱: https : //codesandbox.io/embed/vue-button-action-c5kun
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.