带有引导程序 4 的 VUE 2 - 使用数据切换时单选按钮操作不起作用= "buttons"



我有以下代码:

<template>
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-outline-dark active">
<input type="radio" name="grp" v-model="channel" value="vh1" checked> VH1
</label>
<label class="btn btn-outline-dark">
<input type="radio" name="grp" v-model="channel" value="mtv"> MTV
</label>
</div>
</template>
<script>
export default {
data() {
return {
channel: 'mtv'
}
},
watch: {
channel: function(newValue) {
console.log('value has been changed to ' + newValue);
}
}
}
</script>

当我单击单选按钮时,没有任何反应。但是当我删除样式的"data-toggle="buttons"属性时,它开始工作了!谁能帮我在这里找到工作?

编辑

对于那些不知道的人,数据切换来自引导按钮插件,它为您正在制作的按钮添加了额外的样式和功能。在此处查看文档: https://getbootstrap.com/docs/4.0/components/buttons/#toggle-states

删除data-toggle并为每个输入设置active:class="{ 'active': channel === [value] }"

终于有了解决方案

经过长时间的搜索,我能够想出一种方法来破解按钮。

步骤 1

将上述模板更改为以下内容(从输入中删除 v 模型)

<template>
<div class="btn-group" data-toggle="buttons" v-radio="channel">
<label class="btn btn-outline-dark active">
<input type="radio" name="grp" value="vh1" checked> VH1
</label>
<label class="btn btn-outline-dark">
<input type="radio" name="grp" value="mtv"> MTV
</label>
</div>
</template>

这个解决方案很难找到,而且解决方案非常笨拙,但它完成了工作。

步骤 2(更新于 6/18/2018)

创建指令

就我而言,由于我使用的是单个文件组件,因此我需要通过以下方式引入指令:

收音机.js

export default {
inserted: function (el, binding) {
var btns = $(el).find('.btn');
var radioGrpName = $(btns[0]).find('input')[0].name;
$("input[name='" + radioGrpName + "'][value='" + binding.value + "']").closest('.btn').button('toggle');
},
bind: function (el, binding, vnode) {
var btns = $(el).find('.btn');
btns.each(function () {
$(this).on('click', function () {
var v = $(this).find('input').get(0).value;
(function set(obj, str, val) {
str = str.split('.');
while (str.length > 1) {
obj = obj[str.shift()];
}
return obj[str.shift()] = val;
})(vnode.context, binding.expression, v);
})
})
}
}

这样做是将jquery单击事件绑定到包含v-radio的div中找到的每个单选按钮。我正在做函数集的第二部分(从参考中的答案复制),它检查表达式中是否有任何点,否则它会设置 vnode.context["channel"] 的值,这会更新模型。绑定在加载组件之前挂接到事件,以便它可以准备好触发单选按钮的内部工作。

插入的函数在绑定后,在将组件物理插入父节点期间调用。因此,当您设置初始状态(未触发任何事件)时,组件将自动反映数据中设置的值。

步骤 3

将指令无线电添加到脚本

import radio from '../../directives/radio'
<script>
export default {
directives: {
radio: radio  
},
data() {
return {
channel: 'mtv'
}
},
//you can use computed property, but you need get and set
watch: {
channel: function(newValue) {
console.log('value has been changed to ' + newValue);
}
}
}
</script>

使用这些链接作为参考:

  • 使用 vue 1 的旧自定义指令黑客
  • 从自定义指令更新模型

最新更新