![](/img/trans.png)
[英]How to update state of parent by passing a function as props to its children
[英]Passing parent props to children
我一直在嘗試使用 Vue.js 創建一個“可自定義的表單模板”。 我想應用的邏輯如下:
vueForm
道具並呈現表單。 vueForm
是一個具有特定結構的對象,包含fields
和errors
鍵。value
(用於 v-model)和errors
......這恰好在我們之前提到的vueForm
對象中可用我的問題是我似乎無法從我的custom-input
中訪問在custom-form
中作為道具傳遞的vueForm
對象:(。我嘗試使用提供/注入等將其添加到數據中。到目前為止沒有成功.
任何幫助將不勝感激 :)
謝謝
下面是代碼示例:
成分
// PARENT COMPONENT
Vue.component("custom-form", {
props: {
vueForm: Object,
},
template:
`<form :id="vueForm.id" :method="vueForm.method" action="">
<slot></slot>
</form>`,
});
// CHILD COMPONENT
Vue.component("custom-input", {
props: {
name: String,
type: String,
placeholder: String,
icon: String,
value: [String, Number, Date],
errors: Array,
},
template:
`<div class="field">
<div class="control has-icons-left has-icons-right">
<span class="icon is-small is-left">
<i :class="icon"></i>
</span>
<input
class="input"
:type="type"
:name="name"
:placeholder="placeholder"
v-on:input="$emit('input', $event.target.value)"
>
<span class="icon is-small is-right" v-if="errors.length">
<i class="fas fa-exclamation-triangle"></i>
</span>
<p class="help is-danger" v-for="message in errors">
{{message}}
</p>
</div>
</div>`,
});
VUE
var mainVue = new Vue({
el: "main",
data: {
loginTab: true,
authForm: {
id: "user-form",
method: "POST",
errors: {
non_field_errors: [],
email: [],
password: [],
confirm_password: [],
},
fields: {
email: "",
password: "",
confirm_password: "",
},
},
},
});
HTML
<custom-form :vue-form="authForm"> <!-- Passing authFrom as our vueForm prop -->
<custom-input
name="email"
type="email"
placeholder="Email"
icon="fas fa-envelope"
:value="vueForm.fields.email" <!-- vueForm is not defined :( -->
:errors="vueForm.errors.email" <!-- vueForm is not defined :( -->
></custom-input>
<button
class="button is-primary"
@click.prevent="submitForm"
>
<span class="icon is-small">
<i class="fas fa-check"></i>
</span>
<span>{% trans "Submit" %}</span>
</button>
</custom-form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.