如何在 vue 中绑定“v-model”属性?
Posted
技术标签:
【中文标题】如何在 vue 中绑定“v-model”属性?【英文标题】:How to bind "v-model" property in vue? 【发布时间】:2020-07-15 10:43:43 【问题描述】:我想动态显示输入列表。
我不是在询问使用 v-bind 或 v-model,我想绑定 v-model 属性本身(如 v-bind:v-model)。
这是代码,但它不起作用。
<template>
<div class="form-outside">
<form>
<div v-for="(input, index) in inputs" :key="index">
<div class="caption">input.caption</div>
<input :type="input.type" :v-model="input.model" />
</div>
<div v-if="error" class="error-message">error</div>
<div v-if="kind=='login'" class="suggestion">
Don't have an account?
<nuxt-link to="/signup">Sign up</nuxt-link> instead!
</div>
<div v-if="kind=='signup'" class="suggestion">
Have an account?
<nuxt-link to="/login">Log in</nuxt-link> instead!
</div>
<div v-if="loading" class="loading">Loading</div>
<button @click.prevent="submitted" v-if="!loading">button_text</button>
</form>
</div>
</template>
<script>
export default
name: "AuthForm",
props: ["kind", "error", "loading"],
methods:
submitted()
this.$emit("submitted",
email: this.email,
password: this.password,
confirm_password: this.confirm_password,
full_name: this.full_name,
login: this.login,
username: this.username
);
,
computed:
button_text()
if (this.kind == "login") return "Log in";
if (this.kind == "signup") return "Sign up";
,
inputs()
return this.possible_inputs.filter(
input => input.when == "always" || input.when == this.kind
);
,
data()
return
email: "",
password: "",
confirm_password: "",
full_name: "",
login: "",
username: "",
possible_inputs: [
caption: "Full Name",
type: "text",
when: "signup",
model: this.full_name
,
caption: "Email",
type: "email",
when: "signup",
model: this.email
,
caption: "Email or Username",
type: "text",
when: "login",
model: this.login
,
caption: "Username",
type: "text",
when: "signup",
model: this.username
,
caption: "Password",
type: "password",
when: "always",
model: this.password
,
caption: "Confirm Password",
type: "password",
when: "signup",
model: this.confirm_password
]
;
;
</script>
(这是一些额外的文字,因为 *** 说“看起来你的帖子主要是代码,请添加更多细节”,忽略它)
【问题讨论】:
【参考方案1】:在data()
你不能这样分配model: this.email
所以你需要在mounted()
钩子中分配它,检查下面的代码:
<script>
export default
data()
return
email: "",
password: "",
confirm_password: "",
full_name: "",
login: "",
username: "",
possible_inputs: []
;
,
mounted()
this.possible_inputs = [
caption: "Full Name",
type: "text",
when: "signup",
model: this.full_name
,
caption: "Email",
type: "email",
when: "signup",
model: this.email
,
caption: "Email or Username",
type: "text",
when: "login",
model: this.login
,
caption: "Username",
type: "text",
when: "signup",
model: this.username
,
caption: "Password",
type: "password",
when: "always",
model: this.password
,
caption: "Confirm Password",
type: "password",
when: "signup",
model: this.confirm_password
,
];
,
;
</script>
【讨论】:
以上是关于如何在 vue 中绑定“v-model”属性?的主要内容,如果未能解决你的问题,请参考以下文章