您可以通过将槽props 传递给输入端来执行此操作:
<AddingMethodComponent v-slot="props">
<input v-bind="props"/>
</AddingMethodComponent>
这是的缩写
<AddingMethodComponent>
<template v-slot:default="props">
<input v-bind="props"/>
</template>
</AddingMethodComponent>
然而,在插槽上使用v-model
是危险的.看起来它添加了@update:modelValue
监听器,但没有添加:modelValue
props .因此,它可以在Vue组件上工作一半.但它不能与本地输入一起工作,因为本地输入需要:value
和@input
.
我认为不管怎样,通过专门设置props 和Listener而不是速记v-model
会更好,即如果您使用本机输入:
<slot
:value="textModel"
@input="event => textModel = event.target.value"
></slot>
如果您使用Vue组件:
<slot
:modelValue="textModel"
@update:modelValue="value => textModel = value"
></slot>
这是the updated Stackblitz美元.
更新:事实证明你使用的是Vue 2,其中的事件不是attrs的一部分.所以你必须分别提供props 和听众:
<slot
:props="{value: textValue}"
:on="{input: e => textValue = e}"
/>
然后将它们分别与v-bind
和v-on
绑定:
<AddingMethodComponent v-slot="{props, on}">
<mds-search-field v-bind="props" v-on="on"/>
</AddingMethodComponent>
const SlotComponent = {
template: `
<div>
Here is the slot:
<slot
:props="{value: textValue}"
:on="{input: e => textValue = e}"
/>
Value in parent: <i>{{ textValue }}</i>
</div>
`,
data(){
return {
textValue: 'initial parent value'
}
},
}
const InputComponent = {
template: `
<div>
<input :value="value" @input="$emit('input', $event.target.value)">
</div>
`,
props: ['value'],
emit: ['input']
}
new Vue({
el: '#app',
components: {
SlotComponent,
InputComponent,
},
data() {
return {
test: 'value'
};
},
})
<div id="app">
<slot-component v-slot="{props, on}">
<input-component v-bind="props" v-on="on"/>
</slot-component>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.10/vue.min.js"></script>