最近闲的无聊,用vue来重写自己的平台,以前是用jquery写的,去年用react写了一遍,今年打算用vue来翻写一遍。

react中传递对象到子组件是非常普遍,vue还没传过,写个例子试了试,原来也差不多的。

图底部有4个按钮,通过传入一个json对象到子模板中,子模板渲染相应的按钮控件

这里写图片描述

子模板,goBtn的代码如下,接收一个item对象,根据item里的值来组装代码

//系统常规按钮模板
var goBtn={
    props:{
        btnItem:{
            type:Object,
        }
    },
    methods:{
        //点击按钮事件 并触发父节点传入的事件
        btnClick(btnId){
           this.$emit('btnClick',btnId,event);
        },
        //鼠标移入到按钮中 如果存在图片 则需要变更图片地址
        btnMouseOver(event,imgUrl){
            let imgEl=$(event.target).closest(".btnItem").find("img");
            if(imgEl.get(0)!=null){
                let newImg=imgUrl.split(".svg")[0]+"_hover"+".svg";
                imgEl.attr("src",newImg);
            }
        },
        //鼠标移出按钮时 还原图标
        btnMouseLeave(event,imgUrl){
            let imgEl=$(event.target).closest(".btnItem").find("img");
            if(imgEl.get(0)!=null){
                imgEl.attr("src",imgUrl);
            }
        }
    },
    template: (()=> {
        return  `
             <div class="btnItem" @mouseleave="btnMouseLeave($event,btnItem.img)" @mouseover="btnMouseOver($event,btnItem.img)" @click='btnClick(btnItem.id)'>
                <div class="goBtn">
                <!--如果是svg 则展示图标 如果是字体图标 则设置相应的class-->
                    <div class="btnImg" v-if="btnItem.imgType=='svg'">
                      <img  class="svg14" :src="btnItem.img">
                    </div>
                     <div class="btnImg" v-if="btnItem.imgType=='fontIcon'">
                           <i :class="btnItem.img" aria-hidden="true"></i>
                    </div>
                <div class="btnLabel">{{btnItem.text}}</div>
                </div>
            </div>
        `;
    })()
}

调用模板的代码

   <go-btn :btnItem="item"  v-on:btnClick="btnClick" v-for="item of settingBottomBtn"></go-btn>

vuex中定义按钮集合代码

settingBottomBtn:[
            {text:"首页门户设计",id:"portalSettings",img:"fa fa-university",imgType:"fontIcon"},
            {text:"更多设置",id:"moreSetting",img:"fa fa-paper-plane-o",imgType:"fontIcon"},
            {text:"重置",id:"restSetting",img:"../../svg/reset.svg",imgType:"svg"},
            {text:"关闭",id:"closeSettingPanel",img:"../../svg/closeBtn.svg",imgType:"svg"}
        ],
Logo

前往低代码交流专区

更多推荐