[英]how to create v-model custom component in Nuxt
我在 Nuxt 中對自定義組件進行雙向綁定時遇到問題。 也許我在某個地方犯了一個愚蠢的錯誤。 我將不勝感激
#自定義組件輸入.vue
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" class="input" type="text">
</template>
<script>
export default {
props:{
modelValue:String,
},
}
</script>
<style lang="scss" scoped>
@import '@/assets/_shared.scss';
.input{
padding: 10px 15px;
background: white;
border: 1px solid #cecece;
border-radius: 4px;
}
</style>
#頁面索引.vue
<template>
<section class="new-appeal">
<form class="new-appeal-form">
<label class="new-appeal-form-item">
<Input placeholder="Appeal" v-model.trim="cashier_name"/>
</label>
<Button class="submit">Creare appeal</Button>
</form>
</section>
</template>
<script>
export default {
layout:'main',
data:function(){
return{
cashier_name:''
}
},
}
</script>
如您所見,我正在嘗試進行雙向數據綁定,但不幸的是它不起作用
您缺少發出屬性。
export default {
emits: ['update:modelValue'],
props:{
modelValue:String,
},
}
這很好用並且遵循慣例。
index.vue
<template>
<section class="new-appeal">
<form class="new-appeal-form">
<label class="new-appeal-form-item">
<Input v-model.trim="cashierName" placeholder="Appeal" />
</label>
<Button class="submit">Creare appeal</Button>
</form>
</section>
</template>
<script>
export default {
layout: 'main',
data() {
return {
cashierName: '',
}
},
}
</script>
Input.vue
<template>
<input
:value="cashierName"
class="input"
type="text"
@input="$emit('input', $event.target.value)"
/>
</template>
<script>
export default {
name: 'Input',
props: {
cashierName: {
type: String,
default: '',
},
},
}
</script>
否則,您也可以如下所示(我仍在將cashier_name
重命名為 camelCase 順便說一句)
index.vue
<template>
<section class="new-appeal">
<form class="new-appeal-form">
<label class="new-appeal-form-item">
<Input v-model.trim="cashierName" placeholder="Appeal" />
</label>
<Button class="submit">Creare appeal</Button>
</form>
</section>
</template>
<script>
export default {
layout: 'main',
data() {
return {
cashierName: '',
}
},
}
</script>
Input.vue
<template>
<input
:value="cashierName"
class="input"
type="text"
@input="$emit('update:cashierName', $event.target.value)"
/>
</template>
<script>
export default {
name: 'Input',
// https://vuejs.org/v2/api/#model
model: {
prop: 'cashierName',
event: 'update:cashierName',
},
props: {
cashierName: {
type: String,
default: '',
},
},
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.