Vue弹窗用也可以直接调用Js方法了

news2024/10/25 0:36:55

问题描述

在前端开发中,弹窗开发是一个不可避免的场景。然而,按照正常的逻辑,通过在template模板中先引用组件,然后通过v-if指令控制显隐,进而达到弹窗的效果。然而,这种方法却有一个严重的缺陷,即有较强的代码入侵。如果当前组件存在多个不同的弹框,那么会定义相等数量的显隐变量,给代码维护增加了心智负担。
细心的人会发现,在使用element-ui等前端框架中,我们可以直接调用方法,弹框就会出现,接下来执行不同的逻辑。那么我们的弹框能否可以借鉴一下呢?

解决思路

我们知道,vue的component的本质是js对象,我们可以通过javascript创建组将实例,并渲染到页面上。下面我就基于vue2vue3两种版本实现一个地图选点的弹窗式组件。

vue2的封装方式

封装地图组件

<template>
  <div class="main">
    <div id="container" class="map"></div>
    <div class="tools">
      <div class="ok-button" @click="submit">确定</div>
      <div class="ok-button" @click="exits">取消</div>
    </div>
    <div class="info">
      <span>经度:{{ resultPoint[0] }};维度:{{ resultPoint[1] }}</span>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View, control } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import TileGrid from "ol/tilegrid/TileGrid";
import { defaults as defaultControls } from "ol/control";
import Position from "@/assets/position.png";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { tranMktTo84, trans84ToMkt } from "@/utils/protransform";

export default {
  props: {
    lon: {
      type: Number,
      default: 119.407428,
    },
    lat: {
      type: Number,
      default: 33.904198,
    },
  },
  data() {
    return {
      resultPoint:[this.lon,this.lat],
      vectorFeature: null,
    };
  },
  mounted() {
    let initMkt = trans84ToMkt(this.resultPoint)
    let map = new Map({
      target: "container",
      layers: [],
      controls: defaultControls({ attribution: false, zoom: false }), // 禁用默认的控件
      view: new View({
        center: initMkt, 
        zoom: 16,
        projection: "EPSG:3857",
      }),
    });

    const iconStyle = new Style({
      image: new Icon({
        anchor: [0.55, 1.1],
        src: Position,
      }),
    });
    let vectorFeature = new VectorSource({ features: [] });
    let vector = new VectorLayer({
      source: vectorFeature,
      style: iconStyle,
      id: "point",
    });

    this.loadGdLayer(map)
    let that = this;
    map.on("click", function (event) {
      // 获取点击位置的坐标,并推入 points 数组
      let coord = event.coordinate;
      that.resultPoint = tranMktTo84(coord)
      that.renderPoint(coord,vectorFeature)
    });

    map.addLayer(vector);
    this.renderPoint(initMkt,vectorFeature)
    this.map = map;
  },
  methods: {
    loadGdLayer(map){
      //影像
      map.addLayer(this.createGdLayer("6", true));
      //影像路网注记`
      map.addLayer(this.createGdLayer("8", true));
    },
    //创建高德地图图层
    createGdLayer(layer,visible){
      return new TileLayer({
            title: "高德地图",
            source: new XYZ({
                url: `https://webst0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=${layer}`,
                wrapX: false
            }),
            projection: "EPSG:3857",
            visible
        });
    },
    submit() {
      this.$emit("click", this.resultPoint[0], this.resultPoint[1]);
    },
    exits() {
      this.$emit("close");
    },
    createPointFeature(point) {
      return new Feature({
        geometry: new Point(point),
        name: "position",
      });
    },
    renderPoint(point,vectorFeature){
      vectorFeature.clear();
      vectorFeature.addFeature(this.createPointFeature(point));
    }
  },
};
</script>

<style lang="less" scoped>
.main {
  position: fixed;
  width: 100vw;
  height: 100vh;
  left: 0;
  bottom: 0;
  background-color: #ffffff;
}
#container {
  width: 100%;
  height: 100%;
}
.ok-button {
  text-align: center;
  line-height: 0.36rem;
  height: 0.36rem;
  width: 0.7rem;
  background: #4b74ff;
  border-radius: 15%;
  font-size: 0.2rem;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #ffffff;
  &:hover {
    cursor: pointer;
  }
}
.info {
  position: absolute;
  left: 0.1rem;
  bottom: 0.2rem;
  background-color: rgba(150, 150, 150, 0.1);
  font-size: 0.2rem;
}
.tools {
  position: absolute;
  right: 0.1rem;
  top: 0.1rem;
  display: flex;
  justify-content: space-evenly;
  width: 1.5rem;
}
</style>

这个组件有两个地方需要注意以下:

  • 定义了属性,便于被调用着传递。这里主要传递显示坐标,如果不传递,则显示默认坐标。
  • 对于submitclose方法,通过this.$emit调用父类的方法,这里的方法名分别为clickclose。记主这两个方法名。

封装组件方法

这也是封装的核心

import GetPosition from "@/components/GetPosition.vue";
import { getPoint } from "@/utils/calDistance";
import Vue from "vue";
function createDiv(uuid) {
  const div = document.createElement("div");
  div.style.position = "absolute";
  div.style.zIndex = "1000";
  div.style.backgroundColor = "rbg(255,255,255)"
  div.id = uuid;
  document.body.appendChild(div);
  const childDiv = document.createElement("div");
  div.appendChild(childDiv);
  return childDiv;
}

export const selectPoint= (lon,lat,onClick)=>{
  let uuid = Math.random().toString(36).substring(2);
  const div = createDiv(uuid);
  const app = new Vue({
    render: (h) =>
      h(GetPosition, {
        props: { lon: lon, lat: lat },
        on: {
          click(lon, lat) {
            app.$destroy();
            let div = document.getElementById(uuid);
            div.remove();
            onClick(lon, lat);
          },
          close() {
            app.$destroy();
            let div = document.getElementById(uuid);
            div.remove();
          },
        },
      }),
  }).$mount(div);
}
  • createDiv创建一个渲染的组件,这个组件要作为body的子组件,至于样式要根据设计情况而定。此组件要设置id,这里使用随机ID,便于document.getElementById(uuid)查询。
  • selectPoint是其他组件调用的核心方法。此方面有传入参数和一个回调函数onClick
    • 通过createDiv方法创建vue过载的节点。
    • 创建vue实例,并定义render函数。
    • 回调父组件的emit方法要定义到on中。
    • 在点击确认或者取消按钮,弹窗消失的时候,需要将vue实例销毁app.$destroy(),并将div移除。

调用方式

 clickMap(item) {
     let lon = this.longitude || 117.633757
     let lat = this.latitude || 29.558668
     selectPointInfo(lon,lat,(lon,lat)=>{
       this.longitude = lon
       this.latitude = lat
       item.model = `${lon},${lat}`
     })
}

vue3的封装方式

vue3vue2的不同之处在于创建vue实例上。所以这里只展示调用方法的实例:

export function selectPointInfo(pointInfo:PointInfo,onClick:(item:PointInfo)=>void){
    const div = createDiv()
    const app = createApp(SelectPointVue,{
        pointInfo,
        onClick(item:PointInfo){
            app.unmount();
            div.remove()
            onClick(item)
        },
        onClose(){
            app.unmount();
            div.remove()
        }
    })
    app.mount(div)
}

这里需要注意的地方如下:

  • props直接传递一个对象即可。
  • emit的方法名前要追加on,方法名首字母要大写。例如,在vue组件中有代码this.$emit("click", lon,lat);,那么此处方法应该定义为onClick

vue2和vue3的这两段代码出于不同的项目,所以vue3的核心代码不能直接使用上面的组件。核心逻辑已经列处,需要按需调整。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2222824.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

《纳瓦尔宝典:财富和幸福指南》读书随笔

最近在罗胖的得到听书中听到一本书&#xff0c;感觉很有启发&#xff0c;书的名字叫《纳瓦尔宝典》&#xff0c;从书名上看给人的感觉应该财富知识类、鸡汤爆棚哪类。纳瓦尔&#xff0c;这个名字之前确实没有听说过&#xff0c;用一句话介绍一下&#xff0c;一个印度裔的硅谷中…

【LeetCode】修炼之路-0006-Zigzag Conversion (Z 字形变换)【python】

题目 The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: “PAHNAPLSIIGYIR” …

荣耀电脑管家-系统重装之查询设备序列号

winr输入cmd&#xff0c;再命令行中输入 wmic bios get serialnumber 如下所示

代码随想录算法训练营第六天|454四数相加II、 383赎金信、15三数之和、18四数之和

day06 1. 454四数相加II 首先定义 一个unordered_map&#xff0c;key放a和b两数之和&#xff0c;value 放a和b两数之和出现的次数。遍历大A和大B数组&#xff0c;统计两个数组元素之和&#xff0c;和出现的次数&#xff0c;放到map中。定义int变量count&#xff0c;用来统计 …

YAML格式校验API:免费工具的使用指南

YAML&#xff08;YAML Ain’t Markup Language&#xff09;是一种人类可读的数据序列化格式&#xff0c;广泛用于配置文件、数据交换等场景。由于其简洁的语法和良好的可读性&#xff0c;YAML 在开发和运维领域中越来越受到欢迎。然而&#xff0c;在使用 YAML 时&#xff0c;格…

Xcode文件默认存储位置-使用c++file保存文件默认路径以及设置为路径为当前项目路径

Xcode文件默认存储位置-使用cfile保存文件默认路径以及设置为路径为当前项目路径 1.概述 使用Xcode工具开发时候&#xff0c;遇到C调用file创建文件后&#xff0c;在当前项目中找不到文件路径。这是由于xcode会将文件保存到默认设置的路径。下面是查看文件默认存储路径和修改…

数组中的算法

目录 1.什么是数组 2.数组上的算法 2.1二分查找算法 什么是二分查找算法&#xff1f; 算法步骤 算法时间复杂度 一个问题 例题 题目分析 解题代码 2.2双指针法 什么是双指针法&#xff1f; 例题 题目分析 解题代码 1.什么是数组 数组是在一块连续的内存空间…

C++,STL 047(24.10.24)

内容 对set容器的元素进行查找与统计。 运行代码 #include <iostream> #include <set>using namespace std;void printSet(set<int> &s) {for (set<int>::iterator it s.begin(); it ! s.end(); it){cout << *it << " ";…

linux-牛刀小试

题目一&#xff1a; 1.第一问 首先创建用户tab在超级用户root的终端输入useradd tab 切换到tab用户&#xff1a; 推出重新登录到tab用户或者su – tab切换到tab用户 2.第二问 在桌面创建SHEGNCHAN目录 在SHENGCHAN文件夹下创建相应的文件&#xff1a; 3.第三问 首先&#…

哈希表【闭散列/开散列】

&#x1f33b;个人主页&#xff1a;路飞雪吖~ &#x1f320;专栏&#xff1a;C/C 目录 一、unordered系列关联式容器 &#x1f31f;unordered_map ⭐unordered_map接口说明 二、底层结构 &#x1f31f;哈希概念 &#x1f31f;哈希冲突 &#x1f31f;哈希函数 &#x1f3…

基于Leaflet和SpringBoot的全球国家综合检索WebGIS可视化

目录 前言 一、Java后台程序设计 1、业务层设计 2、控制层设计 二、WebGIS可视化实现 1、侧边栏展示 2、空间边界信息展示 三、标注成果展示 1、面积最大的国家 2、国土面积最小的国家 3、海拔最低的国家 4、最大的群岛国家 四、总结 前言 在前面的博文中&#xff…

【随手笔记】远程升级之如何平衡下载包大小与速率?

1. 远程升级基本信息 使用NB_BC26模组&#xff0c;通过AT指令使用TCP的协议与公司后台交互升级的固件为BIN文件&#xff0c;使用原始固件包升级&#xff0c;未使用差分方式原始固件包有110K,大小左右&#xff0c;固件的存储为外置的FLASH W25Q16,w25q16最小存储单位为页&#…

AListFlutter(手机alist)——一键安装,可在手机/电视上运行并挂载各个网盘

前面提到软路由系统OpenWRT的时候&#xff0c;当时说过可以在OpenWRT里安装alist&#xff0c;然后挂载网盘&#xff0c;这样就可以通过webdav的方式在家庭局域网下的任何设备都可以访问操作这些网盘&#xff0c;摆脱硬盘空间不够的问题。 但alist的官方版本是没有手机版本的&a…

【Java】探秘正则表达式:深度解析与精妙运用

目录 引言 一、基本概念 1.1 元字符 1.2 预定义字符类 1.3 边界匹配符 1.4 数量标识符 1.5 捕获与非捕获分组 二、Java中的正则表达式支持 三、正则表达式的使用示例 3.1 匹配字符串 3.2 替换字符串 3.3 分割字符串 3.4 使用Pattern和Matcher 3.5 捕获组和后向…

我了个超绝MATLAB——基础

由于要参加美赛&#xff0c;不想拖对队友们的后腿&#xff0c;于是一怒之下……怒了一下 创建MATLAB脚本 创建脚本 在主页——新建——脚本 中新建脚本&#xff08;Ctrln&#xff09; 保存 编辑器——保存&#xff08;Ctrls&#xff09; 运行 编辑器——运行&#xff08;F5&…

iOS--利用UITableViewDataSourcePrefetching实现平滑如丝的无限滚动

前言&#xff1a; 相信大家在网络不好的时候使用列表分页的App会获得非常不好的体验&#xff0c;由于网络的问题&#xff0c;会有明显的卡顿&#xff0c;就像抖音等App&#xff0c;那么我们是否能使用一些手段来优化这个体验呢&#xff1f;这里可以用到UITableView中另一个协议…

【案例演示】图像描述大模型示例及概念解释

【案例演示】图像描述大模型示例及概念解释 一、案例演示模型描述期望模型使用方式以及适用范围模型功能演示 二、大模型开源平台概览模型库的定义大模型开源平台 一、案例演示 模型链接&#xff1a;https://modelscope.cn/models/iic/mplug_image-captioning_coco_base_zh 模…

使用 CDN 后 Apache 的日志记录客户真实 IP

经常搭建网站服务器的都知道&#xff0c;在给站点使用了 CDN 后 Web 应用的日志记录里就会只记录 CDN 节点 IP 了&#xff0c;这就没法看到真实客户请求 IP&#xff0c;对于日志分析、运维日常维护来说就有点儿麻烦了&#xff0c;今天明月结合在五洛云服务器上搭建的Apache环境…

短视频账号矩阵系统源码---独立saas技术部署

#短视频账号矩阵系统# #短视频矩阵源码# #短视频账号矩阵系统技术开发# 抖音seo账号矩阵系统&#xff0c;短视频矩阵系统源码&#xff0c; 短视频矩阵是一种常见的视频编码标准&#xff0c;通过多账号一键授权管理的方式&#xff0c;为运营人员打造功能强大及全面的“矩阵式“…

liunx线程互斥

临界资源和临界区 临界资源&#xff1a;多线程执行流共享的资源就叫临界资源。 临界区&#xff1a;每个线程中&#xff0c;访问临界区的代码&#xff0c;就叫临界区。 互斥&#xff1a;任何时候&#xff0c;互斥保证只有一个执行流进入临界区&#xff0c;访问临界资源&#…