使用vue.js + jQuery开发组件

158 篇文章 3 订阅
54 篇文章 6 订阅

本模式有3个要点:
1)利用vue.js实现html封装进组件,让复用可以落地;
2)jquery负责操作dom;
3)js函数模拟面向对象中的类,运行时通过new方式创建对象,将dom标识符和业务数据作为参数传递,提高组件独立性,实现与调用页面解耦,且能够动态渲染。

近期做的一个项目,使用的框架十分古怪。spring boot,但没有使用默认的thymeleaf,而是前后端分离,同时前后端代码却又放在同一个项目工程里。前端使用了vue.js,但与我之前接触到的vue项目很不一样。一般vue项目,除了一个首页,基本都是组件,然后通过import的方式引用组件。组件里包含有html、css,内聚度极高,独立性极强,非常适合复用。但目前这个项目并没有使用组件,或者说,没有一般意义上的、供复用的组件,都是在本页,通过new Vue的方式,创建一个组件,里面只有js,仅供本页面使用。这样的话,所谓的组件基本并无多大意义,之所以用vue,可能只是看中了绑定数据这个便利。总的来说,这是一个四不像框架,大量使用了jquery,中间夹杂着一点vue,属出土文物。

1、一个组件

其实框架使用的vue.js版本并不算太低,是 Vue.js v2.4.1。按道理,搞成一个一般意义上的vue项目应该是可以的。但我对vue不熟悉,项目时间又太紧,未能对框架进行改造。不过由于项目是个业务系统,许多地方有雷同、类似的地方,十分有必要做成可复用组件。下面是一个例子,组件内封装了html,并且可以通过参数方式,将业务ID传入,动态处理和渲染。
在这里插入图片描述

选取城市组件。支持下拉框和复选框组2种方式。对外提供2个方法:
1)获取选取值
2)设置选取值

2、组件完整代码(city.js)

/*
    区域公用插件
    需要jquery和vue.js支撑
    传入参数:
        el,应用vue的dom标识符,如'#city1'
        city,初始区域值(可选)
    返回:
        无。本插件是一个类,使用时构造实例。实例提供2个对外方法
        getCity:获取选中城市,多个城市用“,”分隔
        setCity:指定选中城市
    e.g.

<div><h1>选择区域公共组件</h1></div>
<div>
    <div  id="cityComp1" class="item">
        <div class="note">下拉框(type=0)</div>
        <span>区域</span>
        <citylist id="city1" type="0" ></citylist>
        <div class="btn">
            <input type="button" value="获取结果" οnclick="alert(comp1.getCity('city1'))" />
            <input type="button" value="指定值" οnclick="comp1.setCity('city1','海口')" />
        </div>
    </div>

    <div  id="cityComp2" class="item">
        <div class="note">复选框(type=1)</div>
        <div class="city-container">
            <span class="formCheckGroupText blackText">区域</span>
            <citylist id="city2" type="1" class="bd" id=""></citylist>
        </div>
        <div class="btn">
            <input type="button" value="获取结果" οnclick="alert(comp2.getCity('city2'))" />
            <input type="button" value="指定值" οnclick="comp2.setCity('city2','琼海')" />
        </div>
    </div>
</div>
<script src="city.js" type="text/javascript" charset="utf-8"></script>
<script>
    let comp1 = new CityCompnent('#cityComp1','三亚');
    let comp2 = new CityCompnent('#cityComp2','文昌');
</script>
 */

function CityCompnent(el,city){
    /* 供外部访问的方法 */
    this.getCity = function(id) {
        return $('#' + id).val();
    };
    this.setCity = function(id,city) {
        $('#' + id).val(city);

        if(type === CHECKBOXLIST){
            setChkAll(false);
            if(city !== ALL){
                let chk = getChkObj(city);
                $(chk).prop('checked',true).change();
            }
        }
    };

    /*
        模板内容一定要包含在<div>里
     */
    let DropDownListTpl = `<div :class="myClass">
<select :class="selectClass" class="form-control" :id="id" name="cityV" v-model="city">
    <option v-for="item in citys" :value="item.vtext">{{item.vtext}}</option>
</select></div>`;

    let CheckBoxListTpl = `<div :class="myClass"><input type="hidden" :id="id" name="cityV" v-model="city" />
<label class="form-check-label" v-for="item in citys">
    <input v-if="item.vtext=='${city}'" type="checkbox" checked group="cityGroup" class="form-check-input" :value="item.vcode" v-on:change="changeChk($event.target.value)" />
    <input v-else type="checkbox" group="cityGroup" class="form-check-input" :value="item.vtext" v-on:change="changeChk($event.target.value)" />
    <span>{{item.vtext}}</span>
</label></div>`;

    const ALL = '全部';
    const DROPDOWNLIST = 0;//下拉框
    const CHECKBOXLIST = 1;//checkbox列表

    let type = DROPDOWNLIST;

    let comp = {
        props:["id","type","class","select-class"],
        data() {
            return {
                myClass:this.class ? this.class : '',
                selectClass: this.selectClass ? this.selectClass : '',
                city:city||ALL,//选中城市字符串,以“,”分隔
                citys:[]
            }
        },
        methods:{
            changeChk(c){
                if(c === ALL){//全部
                    let chkAll = getChkObj(ALL);
                    if($(chkAll).prop('checked')){//选了“全部”
                        setChkAll(true);
                    } else {
                        setChkAll(false);
                    }
                } else {
                    let chk = getChkObj(c);
                    if(!$(chk).prop('checked')){//如果有一个选项取消,则“全部”应被取消
                        let chkAll = getChkObj(ALL);
                        $(chkAll).prop('checked',false).change();
                    }
                }
                getChecked(this);
            }
        },
        created(){
            type = getType(this);
            this.$options.template = getTpl(type);//根据属性值选用不同模板

            let _this = this;
            $.ajax({
                type: 'GET',
                url: 获取数据接口地址
                contentType: "application/json",
                success: function (r) {
                    _this.citys = addItem(r.fieldList);
                }
            });
        }
    };

    function getType(_this){
        return (typeof _this.type !== 'undefined' && _this.type * 1 === CHECKBOXLIST) ? CHECKBOXLIST : DROPDOWNLIST;
    }
    function getTpl(type){//动态设置模板
        return (type === CHECKBOXLIST) ? CheckBoxListTpl : DropDownListTpl;
    }
    function addItem(items){//添加选项
        items.splice(0,0,{
            "valueid":0,"vcode":ALL,"vtext":ALL,"taskType":ALL,"status":ALL
        });

        return items;
    }
    function getChkObj(val){
        return $('[group="cityGroup"][value="' + val + '"]')[0];
    }
    function setChkAll(isChecked){
        $('[group="cityGroup"][value!="' + ALL + '"]').each(function(){
            $(this).prop('checked',isChecked).change();
        });
    }
    function getChecked(_this){
        let str = '';
        $('[group="cityGroup"]:checked').each(function(){
            str += ',' + $(this).val();
        });
        str = (str.length > 0) ? str.substr(1) : str;
        _this.city = str.replace(ALL + ',','');
    }

    new Vue({
        el:el,
        components:{
            'citylist': comp //名字(key)一定要是小写
        }
    });
};

3、使用组件完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue组件测试</title>
    <script src="libs/vue.min.js"></script>
    <script src="libs/jquery.min.js"></script>
    <style>
        .item{
            margin-top: 50px;
        }
        .btn{
            margin-top: 15px;
            margin-left: 15px;
        }
        .note{
            background-color: #FFF9E6;
            border: solid 1px #FFD77A;
            padding: 10px;
            font-size: 18px;
            margin-bottom: 10px;
        }
        .city-container{
            width: 460px;
        }
        .bd{
            float: right;
        }
    </style>
</head>
<body>
<div><h1>选择区域公共组件</h1></div>
<div>
    <div  id="cityComp1" class="item">
        <div class="note">下拉框(type=0)</div>
        <span>区域</span>
        
        <!-- 区域组件(下拉框模式)-->
        <citylist id="city1" type="0" ></citylist>
        
        <div class="btn">
            <input type="button" value="获取结果" onclick="alert(comp1.getCity('city1'))" />
            <input type="button" value="指定值" onclick="comp1.setCity('city1','海口')" />
        </div>    
    </div>

    <div  id="cityComp2" class="item">
        <div class="note">复选框(type=1)</div>
        <div class="city-container">
            <span class="formCheckGroupText blackText">区域</span>
            
            <!-- 区域组件(复选框模式)-->
            <citylist id="city2" type="1" class="bd"></citylist>
            
        </div>
        <div class="btn">
            <input type="button" value="获取结果" onclick="alert(comp2.getCity('city2'))" />
            <input type="button" value="指定值" onclick="comp2.setCity('city2','琼海')" />
        </div>
    </div>
</div>
</body>
</html>
<script src="city.js" type="text/javascript" charset="utf-8"></script>
<script>
    let comp1 = new CityCompnent('#cityComp1','三亚');
    let comp2 = new CityCompnent('#cityComp2');
</script>

4、代码解析

1)组件代码
整体结构是一个类

function CityCompnent(el,city){//el,应用vue的dom标识符
	/* 供外部访问的方法  */
	this.getCity = function(id) {
	};
	this.setCity = function(id,city) {
	};
	
	let DropDownListTpl = `下拉框模板`;
	let CheckBoxListTpl = `复选框组模板`;
	
	//组件核心
	let comp = {
	    props:["id","type","class"],
	    data() {
	        return {
	            myClass:this.class ? this.class : '',
	            city:city||ALL,
	            citys:[]
	        }
	    },
	    methods:{
	    },
	    created(){
	        type = getType(this);
	        this.$options.template = getTpl(type);
	        $.ajax({
	            type: 'GET',
	            url: ,
	            contentType: "application/json",
	            success: function (r) {
	            }
	        });
	    }
	};
	
	。。。
	
	//渲染组件
	new Vue({
	    el:el,
	    components:{
	        'citylist': comp //名字(key)一定要是小写
	    }
	});
};

2)使用组件代码

    <script src="libs/vue.min.js"></script>
    <script src="libs/jquery.min.js"></script>

    <div  id="cityComp1" class="item">
        <!-- 区域组件(下拉框模式)-->
        <citylist id="city1" type="0" ></citylist>
    </div>
    <div  id="cityComp2" class="item">
        <!-- 区域组件(复选框模式)-->
        <citylist id="city2" type="1" class="bd"></citylist>
    </div>

	<script src="city.js" type="text/javascript" charset="utf-8"></script>
	<script>
	    let comp1 = new CityCompnent('#cityComp1','三亚');
	    let comp2 = new CityCompnent('#cityComp2');
	</script>

5、小结

我去年下半年一直在用vue,已经有一段时间没有写原始的js了,不想现在又重拾故技。因为之前多少有点认识,有所理解,所以还是能很快进入状态,解决具体的问题。以前用jquery,觉得很好用,操作dom无所不能,不明白为啥还要有vue、react这些东东。但其实,现在明白了,jquery好用,但一般是做成类库的形式,只能做到部分复用。只有封装html和样式的组件,才真正让复用落地。前后端分离,失去服务器端直接支持的前端,最大问题就是代码如何复用。webpack、vue/react等,能够很好地解决这类问题。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值