Vue实现PopupWindow组件

这段时间一直在学习前端技术来完成自己的小项目。在js方面就使用了Vue框架。由于在项目里想实现一个新建地址的PopupWindow效果,便想到可以使用Vue的一些特性来实现。
用到的Vue特性:组件(Component),props传值,slot内容插入,transitions过渡动画,x-templete模板。
直接上代码(完整代码可在链接中下载popupwindow):
html代码(无样式):

<div id="address-choose">
    <div>
      <button @click="showOneBtnWindow()">显示</button>
            </div>
            <new-address-window 
                 v-show="isShowEditWindow" 
                 @close="removeEditWindow()" 
                 :addressregion="addressRegion">
                  <!--使用插槽显示不同的title-->
                 <p slot="edit-window-title">
                    {{editTitle}}
                 </p>
                 <div slot="popup-btn-container">
                    <button>保存</button> 
                    <button>删除</button>
                </div>
            </new-address-window>
        </div>
<!--新建地址popupwindow模板-->
<script type="text/x-template" id="popup-window-address-new">
    <transition name="popup-window-transition">
        <div>
            <slot name="edit-window-title">
                <p>新建收货地址</p>
            </slot>  
      </div>
      <div>
        <p>收货人</p>
        <input type="text" :value="addressregion.name"/>
      </div>
      <div>
        <p>选择地区</p>
        <ul>
            <li>{{addressregion.province}}</li>
            <li>{{addressregion.city}}</li>
            <li>{{addressregion.region}}</li>
        </ul>
      </div>
      <div>
        <p>联系电话</p>
        <input type="text" placeholder="手机号"/>
      </div>
      <div>
         <p>详细地址</p>
         <input type="text" placeholder="如街道、楼层、门牌号等"/>
      </div>
      <div>
        <p>邮政编码</p>
        <input type="text" placeholder="邮政编码(选填)"/>
      </div>
      <div>
        <slot name="popup-btn-container">
            <button class="btn btn-success">保存</button>
            <button class="btn btn-danger">删除</button>
        </slot>
      </div>
   </div>
  </transition>
</script>

js代码:

/*
 * 新建与编辑地址Vue组件popupwindow
 * */
var newAddressWindow = Vue.component("new-address-window",{
    props: ['addressregion'],
    template: "#popup-window-address-new"
})

/*
 * 地址popupwindow的Vue实例
 * */
var chooseAddress = new Vue({
    el: "#address-choose",
    data: {
        isShowEditWindow: true,
        isOneButton: false,
        editTitle: "新建收货地址",
        //填入初始地址信息,组件与改数据绑定
        addressRegion: {
        }
    },
    methods: {
        showOneBtnWindow: function(){  //显示新建收货地址对话框(有一个按钮)
            this.isShowEditWindow = true;
            this.isOneButton = false;
            this.editTitle = "新建收货地址";
        },
        removeEditWindow: function(){   //关闭新建与编辑地址选择对话框
            this.isShowEditWindow = false;
        }
    }
})

至此,一个popupwindow的组件就完成了。在实现一个Vue组件时,可以使用模板来实现组件,我这里采用了x-templete模板实现了组件,同时在组件通也可以使用vue的transition特性加入一些动画效果。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/programerxiaoer/article/details/76325936