需求
做出多组radio
组,来作为选择条件的UI组件,比select
更方便好看。
问题
- 使用了
bootstrap
和vue
,两者存在冲突,将bootstrap
的js去掉。除了要实现Vue
的radio
组件外,因为bootstrap
的js删除了,所以radio
选中的效果没有了,需要自己用Vue
来实现绑定点击效果。(不换掉bootstrap
的js的话Vue的radio
组件事件绑定就会和冲突,进而没反应)
- 自定义组件的
v-model
,没能实现出想要的效果。待实验。
解决方法
1. bootstrap
和vue
冲突
本来想换成bootstrap-vue
的js来用,发现radio的效果不一样了,最后还是要自己写选中效果,索性就把bootstrap
的js去掉了,只用个css。
2. Vue
的radio
组件相关实现
demo
的js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| var temp = '<label class="btn btn-default" :class="{active:checked}" :for="id">{{ label }}' + '<input :name="name" :id="id" type="radio" :value="value" :checked.sync="checked" v-on:click="update" ref="input"></label>'; Vue.component('radio-tag', { template: temp, props: { id: String, name: String, label: String, value: String, checked: Boolean }, methods: { update() { console.log('update'); if (this.$refs['input'].checked) { this.$emit('update', this.value); } } } });
var app = new Vue({ el: '#condition', data: { schools: [{ 'id': 'a', 'name': 'a校' }, { 'id': 'b', 'name': 'b校' }], grades: [{ 'id': 'a1', 'name': '初一' }, { 'id': 'a2', 'name': '初二' }, { 'id': 'a3', 'name': '初三' }], school: 'a', grade: 'a1' }, methods: { updateGrades(value) { this.school = value }, updateClazzes(value) { this.grade = value } } });
|
demo
页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <div class="container"> <div id="condition" class="row clearfix "> <div class="col-md-12 column"> <form role="form" class="form-horizontal"> <div class="form-group form-inline"> <label for="School" class="col-md-4 control-label">学校</label> <div class="btn-group" data-toggle="buttons"> <radio-tag v-for="item in schools" :id="item.id" :name="item.id" :label="item.name" :value="item.id" :checked="school === item.id" v-on:update="updateGrades"></radio-tag> </div> <span>{{school}}</span> </div> <div class="form-group form-inline"> <label for="Grade" class="col-md-4 control-label">年级</label> <div class="btn-group" data-toggle="buttons"> <radio-tag v-for="item in grades" :id="item.id" :name="item.id" :label="item.name" :value="item.id" :checked="grade === item.id" v-on:update="updateClazzes"></radio-tag> </div> <span>{{grade}}</span> </div> </form> </div> </div> </div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue"></script> <script type="text/javascript" src="index.js"></script> </body> </html>
|
小结
- vue的语法缩写
- vue中class绑定
:class="{active:isActive}"
,这个是官方例子
:class="{active:(model==0?true:false)}"
,表达式使用
- 父子组件传值
props
属性用来父往子传值
$emit()
方法用来子往父传值