vue.js 初体验之Chrome 插件开发实录(2)

使用 v-for 指令根据一组数组的选项列表进行渲染。 v-for 指令需要以 item in items 形式的特殊语法, items 是源数据数组并且 item 是数组元素迭代的别名。

而下拉框(select)列表的渲染,就可以使用vue中的v-for方法来渲染下拉列表选项,下拉选项数据写在js中的data对象中的options中。用v-bind方法来绑定option的value值,代码如下所示:

<select v-model="selected"> <option v-for="option in options" v-bind:value="option.value"> {{ option.text }} </option> </select>

在vuejs中可以用 v-model 指令在表单控件元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。这里在select中使用v-model方法来监听选中的值。

为了能预览不同对齐的效果,先在CSS中写好和下拉框中值相同的对应的类名样式,这样当用户选中不同的值的时候能显示不同的效果。

<div v-bind:class="selected"> <div> <p>对齐</p> </div> <div> <p>对齐</p> </div> <div> <p>对齐</p> </div> </div>

下拉框这块功能就这样,简简单单几行代码就实现了。想想要是用jquery或者是原生的js来实现同样的功能,不仅代码量要大而且写起来也没有vuejs这么舒服。

接下来是代码同步功能,即在代码区域显示对应flex对齐的CSS代码。

开始之前先讲讲vuejs中的computed属性方法,可计算属性 (computed properties) 就是不存在于原始数据中,而是在运行时实时计算出来的属性。

对应到我们这个实例,就是当用户选择flexbox不同的对齐方式的时候,及时同步对应的CSS代码到代码预览区域。简单起见,直接把几个不同的代码写到js中:

data: { selected: 'cols-center', cssText:{ 'cols-center' : '\n\r-webkit-justify-content: center;\n\r-ms-flex-pack: center;\n\rjustify-content: center;', 'cols-space-between' : '\n\r-webkit-justify-content: space-between;\n\r-ms-flex-pack: justify;\n\rjustify-content: space-between;', 'cols-space-around' : '\n\r-webkit-justify-content: space-around;\n\r-ms-flex-pack: distribute;\n\rjustify-content: space-around;' }, options: [ { text: '居中对齐', value: 'cols-center'}, { text: '两端对齐', value: 'cols-space-between'}, { text: '间隔相等', value: 'cols-space-around'} ] },

根据不同的名字对应不同的CSS代码。然后使用computed方法来根据用户选取的值实时取出对应的CSS代码:

computed:{ cssMsg:function(){ console.log(this) return this.cssText[this.selected]; } }

完整代码如下:

var typeSelect = new Vue({ el: 'body', data: { selected: 'cols-center', cssText:{ 'cols-center' : '\n\r-webkit-justify-content: center;\n\r-ms-flex-pack: center;\n\rjustify-content: center;', 'cols-space-between' : '\n\r-webkit-justify-content: space-between;\n\r-ms-flex-pack: justify;\n\rjustify-content: space-between;', 'cols-space-around' : '\n\r-webkit-justify-content: space-around;\n\r-ms-flex-pack: distribute;\n\rjustify-content: space-around;' }, options: [ { text: '居中对齐', value: 'cols-center'}, { text: '两端对齐', value: 'cols-space-between'}, { text: '间隔相等', value: 'cols-space-around'} ] }, computed:{ cssMsg:function(){ console.log(this) return this.cssText[this.selected]; } } })

最后在html中绑定通过computed方法得到数据也就是CSS:

<div> <pre> <code> {{ cssMsg }} </code> </pre> </div>

开发好之后,可以直接在chrome中运行来调试。打开扩展面板,勾选开发者模式,然后加载刚开发扩展所在的目录就可以直接运行了。

完整的源代码已上传在附件,可以下下来直接运行。

vue.js 初体验之Chrome 插件开发实录

一个简单的插件就完成了,通过这一个简单的chrome插件就可以体验到vuejs在web开发中简单、优雅的魅力,还有什么理由不用起来呢。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wysjxj.html