问题
I have a component that takes an array of options objects, a name, and a v-model, and puts out a radio input with matching label for each of the options in that array of options.
options = [
{text: "Option 1", value="option-1" },
{text: "Option 2", value="option-2" },
]
"updateValue" : function(){
this.$emit('input', this.$refs.input.value);
}
<template v-for="option in options" >
<input
:value="option.value"
:id="name + option.value"
:name="name"
@input="updateValue()"
ref="input" />
<label :for="name + option.value">{{option.text}}</label>
</template>
I've found a similar pattern in this guide where a v-model is taken and then value emitted by watching the @input event.
I cannot wrap my head around how to do this with a radio-type input. Setting :value="value" as with say a text input would make all the radio values identical, which really doesn't work.
回答1:
Here's an example of a really primitive radio button component that uses v-model to update data when an entry is clicked:
const radio = {
props: ['option', 'value'],
template: `<div @click="onClick">{{ option === value ? 'o' : 'x' }}<slot /></div>`,
methods: {
onClick () {
this.$emit('input', this.option)
}
}
}
new Vue({
el: '#app',
components: {
radio
},
data () {
return {
options: ['red', 'green', 'blue'],
selectedOption: 'red'
}
}
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<div id="app">
<radio v-for="option in options"
v-model="selectedOption"
:option="option"
>
{{ option }}
</radio>
</div>
With this implementation each radio button is passed both the currently selected value (via v-model) as well as the value for that particular option (via option). It uses === inside each radio button to determine whether it is the currently selected option.
Vue's support for native radio button's is described here:
https://vuejs.org/v2/guide/forms.html#Radio
It is effectively the same as my example except that what I've called option it calls value. Don't be confused by the way it uses both v-model and value. While v-model binds to value and input by default it can actually be bound to any prop and event (see https://vuejs.org/v2/api/#model). In the case of native checkboxes and radio buttons it binds to the checked property and the change event (mentioned in https://vuejs.org/v2/guide/forms.html#Basic-Usage).
Update:
I think I may have misunderstood your question. My answer provides relevant background but it may be backwards for what you want. v-model just expands to a prop and an event, so if you want to replace v-model with something else you just need to find out which prop and event it's using and use those directly instead.
来源:https://stackoverflow.com/questions/56781192/vue-js-radio-input-without-v-model