我正在尝试制作一个可重用的 vue 单选按钮组件,该组件将采用变量名称和包含标签和值的对象,然后使用 v-for 呈现单选按钮列表。
我在问题的每一部分都取得了成功,但没有设法将它们结合起来:
//component
const Radio = {
template: '#test',
prop: ['value'],
data () {
return {
selected: this.value
}
},
model: {
prop: 'value',
event: 'change'
},
methods: {
handleClickInput (e) {
this.$emit('change', this.selected)
}
}
}
//app
var app2 = new Vue({
el: '#app2',
data: {
door: '',
doorOptions: {
'Yes': 1,
'No': 0,
}
},
components: { Radio, }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app2">
<radio v-model="door"></radio>
<p>
door = {{door}}
</p>
</div>
<template id="test">
<div>
<input type="radio" value="0" v-model="selected" @change="handleClickInput">0
<input type="radio" value="1" v-model="selected" @change="handleClickInput">1
</div>
</template>
// component
Vue.component('radio-set', {
template: '#radio-set',
props: {
'label-name': '',
'variable': '',
'options': '',
},
methods: {
clicked: function(variable, key, value) {
// none of this is right, it doesn't update the vue data model
window[variable] = value; //assign the new value to the dynamic variable name
selected = value;
this.$emit("click-event", variable) //create the click event for model updating by the parent
}
},
})
//app
var app = new Vue({
el: '#vueApp',
data: {
door:'initial value',
doorOptions: {
'Yes':1,
'No':0,
'Maybe':5,
'A new option':25
},
},
methods: {
buttonClick: function(p1){
console.log(p1+': '+window[p1]); //the variable was assigned inside the child component
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vueApp">
<radio-set
label-name="Radio button set"
variable="door"
:options="doorOptions"
@click-event="buttonClick"
>door: {{door}}
</radio-set>
</div>
<template id="radio-set">
<div>
<label>{{labelName}}:</label>
<button
type="button"
v-for="(val, key) in options"
@click="clicked(variable, key, val)"
>
{{ key }}
</button>
</div>
</template>
任何人都可以提供一些关于我如何前进的指示吗?
最佳答案
正如@PierreSaid 提到的,您可以阅读更多关于v-model
的信息。在自定义组件上使用。
这是另一个使用 input[type="radio"]
的示例并将更改事件发送回父组件。
// component
Vue.component('radio-set', {
template: '#radio-set',
props: {
'label-name': '',
'value': '',
'options': '',
}
})
//app
var app = new Vue({
el: '#vueApp',
data() {
return {
door: null,
doorOptions: {
'Yes': 1,
'No': 0,
'Maybe': 5,
'A new option': 25
}
};
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="vueApp">
<radio-set label-name="Radio button set" v-model="door" :options="doorOptions"></radio-set>
door: {{door}}
</div>
<template id="radio-set">
<div>
<div>{{labelName}}:</div>
<label v-for="(val, key) in options" :key="val">
<input type="radio"
:name="labelName"
:value="val"
:checked="val == value"
@change="$emit('input', val)">
{{ key }}
</label>
</div>
</template>
关于具有单选按钮动态列表的 Vue.js v-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58591134/