vue#reactive JavaScript Examples

The following examples show how to use vue#reactive. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: enhancedArray.js    From holo-schedule with MIT License 6 votes vote down vote up
createEnhancedArray = (target = [], limit = Infinity) => {
  const enhancedArray = reactive(target)

  Object.defineProperty(enhancedArray, 'any', {
    get() {
      return enhancedArray.length > 0
    },
  })

  Object.defineProperty(enhancedArray, 'last', {
    get() {
      return enhancedArray[enhancedArray.length - 1]
    },
  })

  enhancedArray.add = (item = {}) => {
    const indexedItem = { $id: uniqueId(), ...item }
    enhancedArray.push(indexedItem)

    if (enhancedArray.length > limit) {
      enhancedArray.shift()
    }

    return indexedItem
  }

  // Changes made by lodash#remove would not traced by Vue
  enhancedArray.remove = item => {
    const index = enhancedArray.indexOf(item)

    if (index === -1) return

    enhancedArray.splice(index, 1)
  }

  return enhancedArray
}
Example #2
Source File: websocket.js    From p2p-tunnel with GNU General Public License v2.0 6 votes vote down vote up
provideWebsocket = () => {
    const state = reactive({
        connected: false
    });
    provide(provideWebsocketKey, state);

    subWebsocketState((connected) => {
        state.connected = connected;
    });
}
Example #3
Source File: useResizeWidth.js    From ant-simple-pro with MIT License 6 votes vote down vote up
// eslint-disable-next-line
export function useResizeWidth(fn = () => {}) {
  // eslint-disable-line
  const state = reactive({
    width: getWindowtWidth(),
    height: getWindowHeight()
  })

  function onResize() {
    state.width = getWindowtWidth()
    state.height = getWindowHeight()
    fn()
  }

  const onResizeThrottled = throttle(onResize, 300)

  onMounted(() => {
    window.addEventListener('resize', onResizeThrottled)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', onResizeThrottled)
  })

  return {
    ...toRefs(state)
  }
}
Example #4
Source File: register.js    From p2p-tunnel with GNU General Public License v2.0 5 votes vote down vote up
provideRegister = () => {
    const state = reactive({
        ClientConfig: {
            GroupId: '',
            Name: '',
            AutoReg: false,
            UseMac: false,
        },
        ServerConfig: {
            Ip: '',
            UdpPort: 0,
            TcpPort: 0,
        },
        LocalInfo: {
            RouteLevel: 0,
            Mac: '',
            Port: 0,
            TcpPort: 0,
            IsConnecting: false,
            UdpConnected: false,
            TcpConnected: false,
            LocalIp: ''
        },
        RemoteInfo: {
            Ip: '',
            UdpPort: 0,
            TcpPort: 0,
            ConnectId: 0,
        }
    });
    provide(provideRegisterKey, state);

    setInterval(() => {
        if (websocketState.connected) {
            getRegisterInfo().then((json) => {
                state.LocalInfo.UdpConnected = json.LocalInfo.UdpConnected;
                state.LocalInfo.TcpConnected = json.LocalInfo.TcpConnected;
                state.LocalInfo.UdpPort = json.LocalInfo.UdpPort;
                state.LocalInfo.TcpPort = json.LocalInfo.TcpPort;
                state.LocalInfo.Mac = json.LocalInfo.Mac;
                state.LocalInfo.LocalIp = json.LocalInfo.LocalIp;

                state.RemoteInfo.UdpPort = json.RemoteInfo.UdpPort;
                state.RemoteInfo.TcpPort = json.RemoteInfo.TcpPort;
                state.RemoteInfo.Ip = json.RemoteInfo.Ip;
                state.RemoteInfo.ConnectId = json.RemoteInfo.ConnectId;

                state.LocalInfo.IsConnecting = json.LocalInfo.IsConnecting;
                state.LocalInfo.RouteLevel = json.LocalInfo.RouteLevel;
                if (!state.ClientConfig.GroupId) {

                    state.ClientConfig.GroupId = json.ClientConfig.GroupId;
                }
            })
        } else {
            state.UdpConnected = false;
            state.TcpConnected = false;
        }
    }, 300);
}
Example #5
Source File: store.js    From vue-iClient3D_for_Cesium with Apache License 2.0 5 votes vote down vote up
storeState = reactive({
    isViewer: false,   //viewer初始化标志
    changeLayers:0,     //图层改变加载完毕监听
    changeGeometrys:0     //三维分析体改变标志
})
Example #6
Source File: vue3-google-oauth2.js    From vue3-google-oauth2-front-sample with MIT License 5 votes vote down vote up
Vue3GoogleOauth = reactive({
  isInit: false,
  isAuthorized: false,
})
Example #7
Source File: useAsync.js    From ant-simple-pro with MIT License 5 votes vote down vote up
/**
 * useAsync
 * @param  {Promise} pro 异步操作
 * @param  {Object} options 参数
 * @param  {Boolean} [options.manual=false] 是否手动调用
 * @param  {Any} options.initialData 初始化数据
 * @param  {Function} options.onSuccess 成功回调
 * @param  {Function} options.onError 失败回调
 */

export function useAsync(pro, options = {}) {
  const {
    manual = false,
    initialData,
    onSuccess = () => {}, // eslint-disable-line
    onError = console.log
  } = options

  const state = reactive({
    data: initialData || null,
    error: null,
    loading: false
  })

  const run = async () => {
    state.error = null
    state.loading = true
    try {
      const result = await pro()
      state.data = result
      onSuccess()
    } catch (err) {
      onError(err)
      state.error = err
    }
    state.loading = false
  }

  onMounted(() => {
    !manual && run()
  })

  // 从外部主动改变数据
  function mutate(data) {
    state.data = data
  }
  return {
    ...toRefs(state),
    run,
    mutate
  }
}
Example #8
Source File: register.js    From p2p-tunnel with GNU General Public License v2.0 5 votes vote down vote up
provideRegister = () => {
    const state = reactive({
        ClientConfig: {
            GroupId: '',
            Name: '',
            AutoReg: false,
            UseMac: false,
            Encode: false
        },
        ServerConfig: {
            Ip: '',
            UdpPort: 0,
            TcpPort: 0,
            Encode: false
        },
        LocalInfo: {
            RouteLevel: 0,
            Mac: '',
            Port: 0,
            TcpPort: 0,
            IsConnecting: false,
            UdpConnected: false,
            TcpConnected: false,
            LocalIp: ''
        },
        RemoteInfo: {
            Ip: '',
            UdpPort: 0,
            TcpPort: 0,
            ConnectId: 0,
        }
    });
    provide(provideRegisterKey, state);

    setInterval(() => {
        if (websocketState.connected) {
            getRegisterInfo().then((json) => {
                state.LocalInfo.UdpConnected = json.LocalInfo.UdpConnected;
                state.LocalInfo.TcpConnected = json.LocalInfo.TcpConnected;
                state.LocalInfo.UdpPort = json.LocalInfo.UdpPort;
                state.LocalInfo.TcpPort = json.LocalInfo.TcpPort;
                state.LocalInfo.Mac = json.LocalInfo.Mac;
                state.LocalInfo.LocalIp = json.LocalInfo.LocalIp;

                state.RemoteInfo.UdpPort = json.RemoteInfo.UdpPort;
                state.RemoteInfo.TcpPort = json.RemoteInfo.TcpPort;
                state.RemoteInfo.Ip = json.RemoteInfo.Ip;
                state.RemoteInfo.ConnectId = json.RemoteInfo.ConnectId;

                state.LocalInfo.IsConnecting = json.LocalInfo.IsConnecting;
                state.LocalInfo.RouteLevel = json.LocalInfo.RouteLevel;
                if (!state.ClientConfig.GroupId) {
                    state.ClientConfig.GroupId = json.ClientConfig.GroupId;
                }
                if (!state.ServerConfig.Ip) {
                    state.ServerConfig.Ip = json.ServerConfig.Ip;
                    state.ServerConfig.UdpPort = json.ServerConfig.UdpPort;
                    state.ServerConfig.TcpPort = json.ServerConfig.TcpPort;
                }
            })
        } else {
            state.UdpConnected = false;
            state.TcpConnected = false;
        }
    }, 300);
}
Example #9
Source File: geological-body.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
// import models from './models.js'


function scanEffect(props) {
    // 设置默认值数据
    let state = reactive({
        operationType: 'stretch_cut',  //操作类型
        stretchHeight: 1,  //拉伸高度
        modelUrls: null,  //模型配置
        digHeight: 500,
        drillRadius: 400,
        drillHeight: 2000,
        clipType: 'drawClip',
        drawClipMode: 'KeepInside',
    });
    state.modelUrls = [
        {
            id: 1,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer1/features/1.stream",
            color: new Cesium.Color(179 / 255, 179 / 255, 179 / 255, 1)
        },
        {
            id: 2,
            model:  "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer2/features/1.stream",
            color: new Cesium.Color(94 / 255, 179 / 255, 59 / 255, 1)
        },
        {
            id: 3,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer3/features/1.stream",
            color: new Cesium.Color(52 / 255, 94 / 255, 35 / 255, 1)
        },
        {
            id: 4,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer4/features/1.stream",
            color: new Cesium.Color(115 / 255, 115 / 255, 115 / 255, 1)
        },
        {
            id: 5,
            model: "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer5/features/1.stream",
            color: new Cesium.Color(171 / 255, 85 / 255, 66 / 255, 1)
        },
        {
            id: 6,
            model:  "http://www.supermapol.com/realspace/services/data-dizhiti/rest/data/datasources/%E5%9C%B0%E8%B4%A8%E4%BD%93/datasets/Layer6/features/1.stream",
            color: new Cesium.Color(68 / 255, 68 / 255, 68 / 255, 1)
        }
    ];

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let scene, solidModelsProfile, entitie_ids = [];  //剖切
    let drillConeCounts = 0, drillPoints = [];  //钻孔
    let editorBox, geoBox;  //裁剪

    if (storeState.isViewer) {
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
        init()
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
            init()
        }
    });

    function init() {
        scene = viewer.scene;
        scene.logarithmicDepthBuffer = true;
        scene.camera.frustum.near = 0.1;
        scene.globe.show = false;
        viewer.scene.skyAtmosphere.show = false;
        solidModelsProfile = new Cesium.SolidModelsProfile(scene);
        solidModelsProfile.addModels(state.modelUrls);
        console.log(solidModelsProfile)
        solidModelsProfile.addedEvent.addEventListener((param)=>{
            console.log(solidModelsProfile._s3mInstanceCollection.getInstance(state.modelUrls[2].model,3))
        })
          viewer.scene.camera.setView({
            destination: new Cesium.Cartesian3(-2167835.4408299956, 4423497.534529096, 4095839.2845661934),
            orientation: {
                heading: 4.029329438295484,
                pitch: -0.23796647219353817,
                roll: 8.994289757424667e-10
            }
        });
    };

    // 拉伸剖切
    function drawLine() {
        if (!window.handlerPolyline) {
            initHandler("Polyline");
        }
        window.tooltip.showAt(' <p>点击鼠标左键开始绘制</p><p>鼠标右键结束绘制</p><p>可以绘制多条线段</p>', '350px');
        handlerDrawing("Polyline").then(
            res => {
                addCutLine(res.result.object.positions)
                let handlerPolyline = window.handlerPolyline;
                handlerPolyline.polyline.show = false;
                // window.polylineTransparent.show = false; //半透线隐藏
                handlerPolyline.deactivate();
                tooltip.setVisible(false);

                let id = 'geologicalbody_cutline-' + new Date().getTime()
                entitie_ids.push(id);
                viewer.entities.add({
                    id: id,
                    polyline: {
                        positions: res.result.object.positions,
                        width: 2,
                        material: Cesium.Color.fromCssColorString('#51ff00'),
                        // clampToGround: true, //线贴地
                        // classificationType: Cesium.ClassificationType.S3M_TILE, //线面贴对象
                    },
                });
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolyline.activate();

    }
    function addCutLine(positions) {
        let pointArray = [];
        if (positions.length < 2) return;
        for (let i = 0; i < positions.length - 1; i++) {
            pointArray.length = 0;
            pointArray.push(positions[i]);
            pointArray.push(positions[i + 1]);
            solidModelsProfile.addProfileGeometry(pointArray);
        }
    }
    function startCut() {
        tooltip.setVisible(false);
        clearHandlerDrawing('Polyline');
        if (entitie_ids.length === 0) {
            window.tooltip.showAt(' <p>请先绘制剖切的线段</p>', '350px');
            return;
        }
        solidModelsProfile.build();
    }
    function clearCut() {
        tooltip.setVisible(false);
        solidModelsProfile.clearProfile();
        clearHandlerDrawing('Polyline');
        entitie_ids.forEach((id) => { viewer.entities.removeById(id); })
        entitie_ids.length = 0;
    }


    //开挖

    function addProfileGeometry(positions) {
        let point3ds = new Cesium.Point3Ds();
        let points = tool.CartesiantoDegreesObjs(positions);
        points.forEach((point) => {
            let point3d = new Cesium.Point3D(point.longitude, point.latitude, point.height + 1000);
            point3ds.add(point3d);
        })
        let geometry = new Cesium.GeoRegion3D([point3ds]);
        if (state.operationType === 'dig') {
            solidModelsProfile.clippingType = Cesium.ClippingType.KeepOutside;
            geometry.extrudedHeight = -Number(state.digHeight);
            //封底
            let geometry2 = new Cesium.GeoRegion3D([point3ds]);
            geometry2.isLatLon = false;
            geometry2.bottomAltitude = geometry.extrudedHeight;
            solidModelsProfile.addProfileGeometry(geometry2);
        } else {
            // solidModelsProfile.clippingType = Cesium.ClippingType.KeepOutside;
            geometry.extrudedHeight = -7000;
        }
        geometry.isLatLon = false;
        solidModelsProfile.setClipGeometry(geometry);
        //封边
        for (let i = 0; i < positions.length; i++) {
            let singleA = [];
            singleA.push(positions[i]);
            if (i == positions.length - 1) {
                singleA.push(positions[0]);
            } else {
                singleA.push(positions[i + 1]);
            }
            solidModelsProfile.addProfileGeometry(singleA);
            solidModelsProfile.build();
        }
    }

    function drawPolygon() {
        if (!window.handlerPolygon) {
            initHandler("Polygon");
        }
        handlerDrawing("Polygon", false).then(
            res => {
                let handlerPolygon = window.handlerPolygon;
                addProfileGeometry(res.result.object.positions);
                handlerPolygon.polygon.show = false;
                handlerPolygon.polyline.show = false;
                handlerPolygon.deactivate();
            },
            err => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
    };

    function startDig() {
        clearDig();
        drawPolygon()
    }

    function clearDig() {
        tooltip.setVisible(false);
        solidModelsProfile.clearProfile();
        clearHandlerDrawing();
    }

    //钻孔
    function startDrilling() {
        clearDrilling();
        viewer.enableCursorStyle = false;
        viewer._element.style.cursor = "";
        document.body.classList.add("measureCur");
        window.tooltip.showAt(' <p>点击鼠标左键确认钻孔位置</p><p>鼠标右键结束绘制并执行钻孔</p>', '350px');
        console.log(1)
        viewer.eventManager.addEventListener("CLICK", click_point, true);
        viewer.eventManager.addEventListener("RIGHT_CLICK", click_right, true);
    };

    function click_point(e) {
        let position = viewer.scene.pickPosition(e.message.position);
        addDrillCone(position);
        drillPoints.push(position)
    }

    function click_right(e) {
        window.tooltip.setVisible(false);
        document.body.classList.remove("measureCur");
        let points = tool.CartesiantoDegreesObjs(drillPoints);
        points.forEach((point) => {
            let geoCylinder = new Cesium.GeoCylinder(Number(state.drillRadius), Number(state.drillRadius), Number(state.drillHeight));
            let height = Number(state.drillHeight)/2;
            geoCylinder.geoPosition = new Cesium.Point3D(point.longitude, point.latitude, point.height-height);
            solidModelsProfile.addProfileGeometry(geoCylinder);
        })
        for (let i = 1; i <= drillConeCounts; i++) {
            viewer.entities.removeById('Drill_Point-' + i);
        }
        solidModelsProfile.build();
        viewer.eventManager.removeEventListener("CLICK", click_point);
        viewer.eventManager.removeEventListener("RIGHT_CLICK", click_right);
    }

    function clearDrilling() {
        tooltip.setVisible(false);
        solidModelsProfile.clearProfile();
        document.body.classList.remove("measureCur");
        for (let i = 1; i <= drillConeCounts; i++) {
            viewer.entities.removeById('Drill_Point-' + i);
        }
        viewer.eventManager.removeEventListener("CLICK", click_point);
        viewer.eventManager.removeEventListener("RIGHT_CLICK", click_right);
        drillConeCounts = 0;
        drillPoints.length = 0;
    }
    // 绘制转空点
    function addDrillCone(position) {
        drillConeCounts++;
        viewer.entities.add({
            id: 'Drill_Point-' + drillConeCounts,
            position: position,
            cylinder: {
                length: 100,
                topRadius: Number(state.drillRadius),
                bottomRadius: Number(state.drillRadius),
                material: Cesium.Color.fromCssColorString("#d60000"),
            }
        });
    }

    //裁剪
    function startClip() {
        clearClip();
        solidModelsProfile.clippingType = Cesium.ClippingType[state.drawClipMode];
        if (state.clipType === 'drawClip') {
            drawPolygon()
            return;
        }
        BoxClipByEitor()
    }

    function clearClip() {
        clearDig();
        clearHandlerDrawing('Box');
        if (editorBox) {
            editorBox.deactivate();
            editorBox.destroy()
            editorBox = null;
        }
    }

    //box裁剪

    function BoxClipByEitor() {
        if (editorBox) {
            editorBox.deactivate();
        }
        tooltip.showAt(' <p>点击鼠标左键开始绘制box底面</p><p>然后移动鼠标绘制box高度</p><p>点击鼠标右键结束绘制</p>', '350px');
        if (!window.handlerBox) {
            initHandler("Box");
        }
        handlerDrawing("Box", false).then(
            res => {
                let handlerBox = window.handlerBox;
                updateClipBox(res.result.object);
                handlerBox.deactivate();
            },
            err => {
                console.log(err);
            }
        );
        window.handlerBox.activate();
    };

    function updateClipBox(object) {
        object.show = false;
        //绘制的盒子裁剪模型
        let newDim = object.box.dimensions.getValue();
        let position = Cesium.Cartographic.fromCartesian(object.position.getValue(0));
        geoBox = new Cesium.GeoBox(newDim.x, newDim.y, newDim.z);
        geoBox.geoPosition = new Cesium.Point3D(Cesium.Math.toDegrees(position.longitude),
            Cesium.Math.toDegrees(position.latitude), position.height);
        solidModelsProfile.addProfileGeometry(geoBox);
        solidModelsProfile.build();
        // 编辑盒子
        if(!editorBox){
            editorBox = new Cesium.BoxEditor(viewer, object);
            editorBox.color = Cesium.Color.WHITE.withAlpha(0.0);//设置盒子透明
            editorBox.hoverColor = Cesium.Color.BLUE;//设置编辑轴的选中色
            let editBoxEvt = function (e) {
                let newDim = e.dimensions;
                geoBox.geoWidth = newDim.y;
                geoBox.geoHeight = newDim.z;
                geoBox.geoLength = newDim.x;
                let position = tool.CartesiantoDegrees(e.position);
                geoBox.geoPosition = new Cesium.Point3D(position[0],position[1],position[2]);
                geoBox.geoRotationZ = editorBox.hpr.heading  * (180 / Cesium.Math.PI);
            };
            editorBox.editEvt.addEventListener(editBoxEvt);
        }else{
            editorBox.setEditObject(object) //
        }
        editorBox.activate();
    }


    //叠加体元



    function clearAll() {
        clearCut();
        clearClip();
        clearDrilling()
    }

    // 监听
    watch(() => state.modelUrls, val => {
        solidModelsProfile.addModels(val);
    });
    watch(() => state.stretchHeight, val => {
        if (!state.modelUrls || state.modelUrls.length == 0) return;
        for (let model of state.modelUrls) {
            let url = model.model;
            let instance = solidModelsProfile._s3mInstanceCollection._group[url].instances._array[0];
            instance.updateScale(new Cesium.Cartesian3(1, 1, Number(val)));
        }
    });
    watch(() => state.operationType, val => {
        clearAll();
    });
    watch(() => state.drawClipMode, val => {
        solidModelsProfile.clippingType = Cesium.ClippingType[val];
    });
    watch(() => state.clipType, val => {
        clearClip()
    });
    // 销毁
    onBeforeUnmount(() => {
        solidModelsProfile.clear()
        viewer.scene.globe.show = true;
        viewer.scene.skyAtmosphere.show = true;
        clearAll();
        scene = null;
        solidModelsProfile = null;
        geoBox= null;
    });


    return {
        ...toRefs(state),
        drawLine,
        startCut,
        clearCut,
        startDig,
        clearDig,
        startDrilling,
        clearDrilling,
        startClip,
        clearClip,
    };
}
Example #10
Source File: index.jsx    From ant-simple-pro with MIT License 4 votes vote down vote up
QueryTemplate = defineComponent({
  emits: ['submit', 'reset'],
  props: {
    options: {
      type: Array,
      default: () => [
        {
          title: '日期',
          fieldName: 'date',
          type: 'timeRangeSelection',
          optionList: [],
          labelName: '',
          valueName: '',
          childrenName: ''
        }
      ]
    },
    name: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    const formRef = ref()
    // default form fields
    const defaultForm = {}
    const form = reactive(defaultForm)

    onMounted(() => {
      for (let i = 0; i < props.options.length; i++) {
        const item = props.options[i] // eslint-disable-line
        defaultForm[item.fieldName] = typeof item.defaultValue !== 'undefined' ? item.defaultValue : ''
      }

      const filteredOptions = props.options.filter(item => item.defaultValue) || []
      if (filteredOptions.length) {
        filteredOptions.forEach(item => {
          if (item.type === 'monthDatePicker') {
            Object.assign(form, {
              [item.fieldName]: moment(item.defaultValue, 'YYYY-MM')
            })
          }
          // else {
          //   Object.assign(form, {
          //     [item.fieldName]: moment(item.defaultValue)
          //   })
          // }
        })
      }
    })

    function onFinish(value) {
      const formData = Object.assign({}, value)
      try {
        props.options.forEach(item => {
          const rangeValue = value[item.fieldName]
          switch (item.type) {
            case 'showTimeRangePicker': {
              formData[item.fieldName] =
                rangeValue && rangeValue.length
                  ? rangeValue.map(item => {
                      if (typeof item === 'string') {
                        return item
                      }
                      return item.format('YYYY-MM-DD HH:mm:ss')
                    })
                  : []
              break
            }

            case 'timeRangeSelection': {
              formData[item.fieldName] =
                rangeValue &&
                rangeValue.length &&
                rangeValue.map(item => {
                  if (typeof item === 'string') {
                    return item
                  }
                  return item.format('YYYY-MM-DD')
                })
              break
            }

            case 'monthDatePicker': {
              formData[item.fieldName] = rangeValue && moment(rangeValue).format('YYYY-MM')
              break
            }

            case 'dayDatePicker': {
              formData[item.fieldName] = rangeValue && rangeValue.format && rangeValue.format('YYYY-MM-DD')
              break
            }

            default: {
              // ...
            }
          }
        })
      } catch (error) {
        console.log(error)
      }
      emit('submit', formData)
    }

    function onReset() {
      formRef.value?.resetFields()
      emit('reset', toRaw(form))
    }

    function disabledDate(current) {
      return current && current > moment().endOf('day')
    }

    function getTemplateByType(type, opts) {
      const templateObj = {
        input: <a-input v-model={[form[opts.fieldName], 'value']} placeholder={opts.placeholder || '请填写'}></a-input>,
        select: (
          <a-select
            v-model={[form[opts.fieldName], 'value']}
            placeholder={opts.placeholder || '请填写'}
            onChange={opts.onChange}
          >
            {opts.optionList?.map((item, index) => (
              <a-select-option key={index} value={item[opts.valueName]}>
                {item[opts.labelName]}
              </a-select-option>
            ))}
          </a-select>
        ),
        cascader: (
          <a-cascader
            v-model={[form[opts.fieldName], 'value']}
            options={opts.optionList}
            placeholder={opts.placeholder || '请填写'}
            fieldNames={{
              label: opts.labelName,
              value: opts.valueName,
              children: opts.childrenName
            }}
            changeOnSelect
          ></a-cascader>
        ),
        timeRangeSelection: (
          <TimeRangeSelection
            v-model={[form[opts.fieldName], 'value']}
            placeholder={opts.placeholder}
          ></TimeRangeSelection>
        ),
        showTimeRangePicker: (
          <a-range-picker
            v-model={[form[opts.fieldName], 'value']}
            onChange={opts.onChange}
            placeholder={opts.placeholder}
            showTime
          ></a-range-picker>
        ),
        monthDatePicker: (
          <a-month-picker
            v-model={[form[opts.fieldName], 'value']}
            onChange={opts.onChange}
            placeholder={opts.placeholder || '请填写'}
            disabledDate={disabledDate}
          ></a-month-picker>
        ),
        dayDatePicker: (
          <a-date-picker
            v-model={[form[opts.fieldName], 'value']}
            mode="date"
            onChange={opts.onChange}
            placeholder={opts.placeholder || '请填写'}
            disabledDate={disabledDate}
          ></a-date-picker>
        )
      }
      const template = templateObj[type]
      if (template) {
        return template
      }
      return (
        <a-input
          v-model={[form[opts.fieldName], 'value']}
          onChange={opts.onChange}
          placeholder={opts.placeholder || '请填写'}
        ></a-input>
      )
    }

    return () => {
      return (
        <a-form ref={formRef} model={form} onFinish={onFinish} class="search-template" name={props.name}>
          <a-row gutter={[15, 15]}>
            {props.options.map((item, index) => (
              <a-col xs={24} sm={12} md={12} lg={8} xl={props.options.length > 3 ? 6 : 8} key={index}>
                <a-form-item
                  label={item.title}
                  name={item.fieldName}
                  data-label={item.title}
                  data-name={item.fieldName}
                >
                  {getTemplateByType(item.type, item)}
                </a-form-item>
              </a-col>
            ))}
            <a-col xs={24} sm={12} md={12} lg={8} xl={props.options.length > 3 ? 6 : 8}>
              <a-form-item>
                <a-button type="primary" htmlType="submit">
                  查询
                </a-button>
                <a-button class="ml10" onClick={onReset}>
                  重置
                </a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      )
    }
  }
})
Example #11
Source File: clip-polygon.js    From vue-iClient3D_for_Cesium with Apache License 2.0 4 votes vote down vote up
//简单局部状态管理

function clipPolygonAnalysis(props) {
    // 设置默认值数据
    let state = reactive({
        clipModelPolygon: 'ClipInside',//裁剪模式js
        isEdit: false,//是否编辑
        isEditZ: false,
        lineVisible: true,//是否显示绘制线
    });

    // 传入props改变默认值
    if (props) {
        for (let key in props) {
            if (state.hasOwnProperty(key)) {
                state[key] = props[key]
            } else {
                tool.Message.errorMsg(resource.AttributeError + key);
            }
        }
    }

    // 初始化数据
    let clipMode = Cesium.ModifyRegionMode.CLIP_INSIDE;   //裁剪模式值 外部: Cesium.ModifyRegionMode.CLIP_OUTSIDE;
    let layers,tipFlag = true;
    let polygonPosition = [];

    /*
     ***裁剪平面分析模块***
    */

    //初始化分析区域 (后面有需要可以添加监听)
    if (props && props.polygonPositions) {
        clipPolygonUpdate(props.slopePositions);
    }
    if (storeState.isViewer) {
        layers = viewer.scene.layers.layerQueue;
        if (!window.tooltip) {
            window.tooltip = createTooltip(viewer._element);
        }
    }
    //viewer 初始化完成的监听
    watch(() => storeState.isViewer, val => {
        if (val) {
            layers = viewer.scene.layers.layerQueue;
            if (!window.tooltip) {
                window.tooltip = createTooltip(viewer._element);
            }
        }
    })

    // 分析
    function clipPolygon(e) {
        e.preventDefault();
        tooltip.setVisible(false);
        if (tipFlag) {   //只提示一次
            tooltip.showAt(' <p>点击鼠标左键开始绘制多边形</p><p>点击鼠标右键结束绘制</p>', '230px');
            tipFlag = false
        }
        if (!layers) {
            layers = viewer.scene.layers.layerQueue;
        }
        for (let layer of layers) {
            layer.selectEnabled = false;
            // 设置被裁剪对象的颜色
            layer.clipLineColor = new Cesium.Color(1, 1, 1, 0);
        }
        if (!window.handlerPolygon) {
            initHandler("Polygon");
        }
        handlerDrawing("Polygon", state.lineVisible).then(
            (res) => {
                clipPolygonUpdate(res.positions)
                let handlerPolygon = window.handlerPolygon;
                handlerPolygon.polygon.show = false;
                handlerPolygon.polyline.show = false;
                handlerPolygon.deactivate();
                if (state.isEdit) {
                    Edit(polygonPosition, state.isEditZ, clipPolygonUpdate);
                }
            },
            (err) => {
                console.log(err);
            }
        );
        window.handlerPolygon.activate();
        if (!scene.pickPositionSupported) {
            tool.Message.errorMsg(resource.NoPickPositionSupported);
        }
    };
    // 更新
    function clipPolygonUpdate(p) {
        polygonPosition = p;
        for (let layer of layers) {
            layer.setModifyRegions([p], clipMode);
        }
    };

    // 清除
    function clearClipPolygon(e) {
        e.preventDefault();
        polygonPosition = [];
        tooltip.setVisible(false);
        if (!window.handlerPolygon) return;
        clearHandlerDrawing("Polygon");
        for (let layer of layers) {
            layer.clearModifyRegions();
        }
    };
    // 监听
    watch(() => state.clipModelPolygon, val => {
        switch (val) {
            case "ClipInside":
                clipMode = Cesium.ModifyRegionMode.CLIP_INSIDE;
                break;
            case "ClipOutside":
                clipMode = Cesium.ModifyRegionMode.CLIP_OUTSIDE;
                break;
            default:
                break;
        }
        if (polygonPosition.length > 0) {
            clipPolygonUpdate(polygonPosition);
        }
    });
    watch(() => state.isEdit, val => {
        if (val && window.handlerPolygon) {
            Edit(polygonPosition, state.isEditZ, clipPolygonUpdate);
        } else {
            clearEditHandler("Polygon");
            if (window.handlerPolygon && window.handlerPolygon.polygon) {
                window.handlerPolygon.polygon.show = false;
            }
        }
    });
    watch(() => state.isEditZ, val => {
        if (window.editHandler) {
            window.editHandler.isEditZ = val;
        }
    });


    // 销毁
    onBeforeUnmount(() => {
        layers = undefined;
    })

    return {
        ...toRefs(state),
        clipPolygon,
        clearClipPolygon,
        polygonPosition
    };
}