改成vue2的watch怎么写
时间: 2023-12-28 16:33:24 浏览: 69
在Vue 2中,您可以使用`$watch`方法来实现类似的效果。以下是如何使用`$watch`来替代Vue 3中的`watch`函数:
```javascript
this.$watch(
function() {
return this.pageData;
},
function() {
this.queryApp();
},
{
deep: true,
immediate: true
}
);
```
在Vue 2中,`this.$watch`接受三个参数:要侦听的属性、回调函数和选项对象。请确保在组件的上下文中使用`this.$watch`。
相关问题
vue3 watch中调用方法报错
在Vue3中,当在watch中使用箭头函数时,会导致this无法访问到。这是因为箭头函数没有自己的this,它会继承外部作用域的this。所以在watch中使用箭头函数时,this指向的是外部作用域,而不是Vue实例。为了解决这个问题,你需要将箭头函数改成普通的函数形式。例如,将watch中的箭头函数改成function形式,如下所示:
```javascript
watch: {
inputValue: function(newValue) {
console.log(newValue);
this.getInfo();
}
},
```
这样就可以正确地访问到this,并调用相应的方法了。[1][2]
另外,如果你想了解更多关于watch的使用方式,可以参考Vue官方文档中关于watch的部分。[2]
将代码全部改成vue3不允许省略代码
为了将提供的 Vue 2 代码转换为 Vue 3 代码,我们需要进行一些调整,包括使用 Composition API 和 Vue 3 提供的新特性。以下是完全转换后的 Vue 3 代码:
```javascript
<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import store from '@/store/';
import { getAction } from '@/api/manage';
import { gcoordTransform } from '@/utils/gcoordTransform';
import L from 'leaflet';
const locationIcon = L.icon({
iconUrl: require('@/assets/inspection/location.svg'),
iconSize: [60, 64],
iconAnchor: [25, 55]
});
// 数据
const ciLayer = ref(null);
const resizeFalg = ref(false);
const leafletMap = ref(null);
const layer = ref(null);
const dropTrigger = ref('');
const replaceFields = { title: 'name', key: 'id' };
const deviceTreeData = ref([]);
const currentPipelinetId = ref('');
const pipelinePosLen = ref(0);
const currentPipeline = ref({});
const selectedKeysPipeline = ref([]);
const treeParam = ref({ pageNo: 1, pageSize: 1000, keyword: '' });
const pointList = ref([]);
const currentDeviceId = ref('');
const devicePosLen = ref(0);
const currentDevice = ref({});
const rightVisible = ref(false);
const deviceTypeList = ref([]);
const selectedKeysDevice = ref([]);
const deviceNameChecked = ref(false);
const tableScrollHeight = ref(480);
const visibleTemp = ref(0);
const showSearchInput = ref(false);
const addrInput = ref('');
const addrMarkerGroup = ref([]);
const fullscreen = ref(false);
const linesDirectionGroup = ref([]);
const directionChecked = ref(false);
const lineList = ref([]);
const needCloseDevices = ref([]);
const rightMeasurementVisible = ref(false);
const drawGroupPolyline = ref(null);
const drawGroupPolygon = ref(null);
const showPolylines = ref([]);
const showPolygons = ref([]);
const showGroupPolyline = ref(null);
const showGroupPolygon = ref(null);
// 过滤器转换为方法
const pipelineColor = (type) => {
switch (type) {
case 1:
return '#950000';
case 2:
return '#FF000D';
case 3:
return '#FFB40A';
case 4:
return '#FF6C00';
case 5:
return '#772FEB';
case 6:
return '#52C41A';
case 7:
return '#13C2C2';
case 8:
return '#1890FF';
default:
return '#1890FF';
}
};
// 方法
const getMap = async () => {
leafletMap.value = L.map('mapid', {
zoom: 14,
center: store.getters.gisMapCenter,
boxZoom: true,
zoomControl: false,
doubleClickZoom: false,
attributionControl: false,
preferCanvas: true
});
leafletMap.value.on('zoom', (e) => {
leafletMap.value.removeLayer(devciceGroup.value);
});
leafletMap.value.on('zoomend', (e) => {
showDeviceMarkers(pointList.value, false);
});
layer.value = L.tileLayer('//webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
maxZoom: 20,
maxNativeZoom: 18,
minZoom: 3,
attribution: "高德地图 AutoNavi.com",
subdomains: "1234"
}).addTo(leafletMap.value);
L.control.zoom({ zoomInTitle: '放大', zoomOutTitle: '缩小', position: 'bottomright' }).addTo(leafletMap.value);
const autoOptions = { input: "addrInput" };
const auto = new AMap.Autocomplete(autoOptions);
new AMap.PlaceSearch({ map: leafletMap.value });
AMap.event.addListener(auto, "select", (e) => {
leafletMap.value.removeLayer(addrMarkerGroup.value);
if (e.poi.location) {
const latlng = [e.poi.location.lat, e.poi.location.lng];
leafletMap.value.setView(latlng);
const marker = L.marker(latlng, { icon: locationIcon });
addrMarkerGroup.value = L.layerGroup([marker]);
leafletMap.value.addLayer(addrMarkerGroup.value);
} else {
alert('您输入的内容查询不到相关地址!');
}
});
leafletMap.value.pm.setLang('zh');
};
const showMap = (val) => {
leafletMap.value.removeLayer(layer.value);
if (val === 1) {
layer.value = L.tileLayer('//webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
maxZoom: 20,
maxNativeZoom: 18,
minZoom: 3,
attribution: "高德地图 AutoNavi.com",
subdomains: "1234"
}).addTo(leafletMap.value);
} else {
layer.value = L.layerGroup([
L.tileLayer('//webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', {
maxZoom: 20,
maxNativeZoom: 18,
minZoom: 3,
attribution: "高德地图 AutoNavi.com",
subdomains: "1234"
}),
L.tileLayer('//webst0{s}.is.autonavi.com/appmaptile?style=8&x={x}&y={y}&z={z}', {
maxZoom: 20,
maxNativeZoom: 18,
minZoom: 3,
attribution: "高德地图 AutoNavi.com",
subdomains: "1234",
opacity: 0.5
})
]).addTo(leafletMap.value);
}
};
const geocoderCalc = (lng, lat) => {
return new Promise((resolve, reject) => {
const geocoder = new AMap.Geocoder({ city: "010", radius: 1000 });
geocoder.getAddress([lng, lat], (status, result) => {
if (status === 'complete' && result.regeocode) {
resolve(result.regeocode.formattedAddress);
} else {
alert('根据经纬度查询地址失败');
}
});
});
};
const dropStatus = (visible) => {
if (!visible) dropTrigger.value = '';
};
const handleClose = () => {
dropTrigger.value = '';
};
const dragControllerDivVertical = () => {
const resize = document.getElementsByClassName('resize');
const left = document.getElementsByClassName('left');
const mid = document.getElementsByClassName('right');
const box = document.getElementsByClassName('inspection');
for (let i = 0; i < resize.length; i++) {
resize[i].onmousedown = (e) => {
resize[i].style.background = '#F0F2F5';
const startX = e.clientX;
resize[i].left = resize[i].offsetLeft;
document.onmousemove = (e) => {
const endX = e.clientX;
const moveLen = resize[i].left + (endX - startX);
const maxT = box[i].clientWidth - resize[i].offsetWidth;
if (moveLen < 250) moveLen = 250;
if (moveLen > maxT - 550) moveLen = maxT - 550;
resize[i].style.left = moveLen;
for (let j = 0; j < left.length; j++) {
left[j].style.width = moveLen + 'px';
mid[j].style.width = (box[i].clientWidth - moveLen - 10) + 'px';
}
};
document.onmouseup = () => {
resize[i].style.background = '#F0F2F5';
document.onmousemove = null;
document.onmouseup = null;
};
};
}
};
const dragControllerDivHorizon = () => {
const resize = document.getElementsByClassName('left-resize');
const left = document.getElementsByClassName('left-tree');
const mid = document.getElementsByClassName('left-table');
const box = document.getElementsByClassName('left');
for (let i = 0; i < resize.length; i++) {
resize[i].onmousedown = (e) => {
const startY = e.clientY;
resize[i].top = resize[i].offsetTop;
document.onmousemove = (e) => {
const endY = e.clientY;
const moveLen = resize[i].top + (endY - startY);
left[i].style.height = moveLen - 25 + 'px';
mid[i].style.height = (box[i].clientHeight - moveLen) + 'px';
if (currentDeviceId.value || currentPipelinetId.value) {
tableScrollHeight.value = box[i].clientHeight - moveLen;
}
};
document.onmouseup = () => {
resize[i].style.background = '#F0F2F5';
document.onmousemove = null;
document.onmouseup = null;
};
};
}
};
const scroll = () => {
const scrolled = Math.abs(
$refs.leftContent.scrollHeight - document.getElementsByClassName('left-tree')[0].clientHeight - $refs.leftContent.scrollTop
);
if (scrolled <= 1 && openLoading.value) {
spinVisible.value = true;
treeParam.value.pageNo++;
handleTabsChange(activeKey.value, 'concat');
}
};
const isDevice = (text) => {
return text.split("_");
};
const deviceStatusColor = (status) => {
switch (status) {
case '2':
return '#d94242';
case '0':
return '#848587';
default:
return '#5ea4ff';
}
};
const getDevicesInfoToId = (id) => {
return new Promise((resolve, reject) => {
if (devicePosLen.value == 3) {
getAction('/web/gisInspectionEquipment/queryById', { id: id }).then((res) => {
if (res.success) {
currentDevice.value = res.result;
resolve(res.result);
}
});
}
});
};
const getPipeLineInfoToId = (id) => {
return new Promise((resolve, reject) => {
getAction('/web/gisInspectionPipeline/list', { id: id }).then((res) => {
if (res.success) {
const val = res.result.records[0];
resolve(val);
}
});
});
};
const calcPointList = () => {
pointList.value.forEach((list, i) => {
list.data.forEach((item) => {
deviceStatusArr.value?.forEach((deviceStatusItem) => {
if (deviceStatusItem.id === item.id) {
item.status = deviceStatusItem.status;
}
});
if (cliqueDeviceId.value.includes(item.id)) {
item.iconSize = 2;
if (cliqueDeviceId.value.length === 1) {
const latlng = gcoordTransform(item.latlng[0], item.latlng[1]);
leafletMap.value.setView(latlng);
}
} else {
item.iconSize = 1;
}
if (needCloseDevices.value.includes(item.id)) {
item.needCloseIcon = true;
} else {
item.needCloseIcon = false;
}
});
});
if (devicePosLen.value == 2) {
const index = deviceTypeList.value.indexOf(currentDevice.value.code);
pointList.value[index].data.forEach((v) => {
v.iconSize = 2;
});
}
if (devicePosLen.value == 3) {
const index = deviceTypeList.value.indexOf(currentDevice.value.gisInspectionEquipmentTypeId);
pointList.value[index].data.forEach((v) => {
if (v.id == currentDeviceId.value) {
v.iconSize = 2;
}
});
}
showDeviceMarkers(pointList.value);
};
const scrollToSelectedNode = (name) => {
nextTick(() => {
const selectedNodeElement = document.querySelector(`[title="${name}"]`);
if (selectedNodeElement) {
selectedNodeElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
});
};
const cancelVis = (e) => {
if (rightVisible.value) {
const cdom = document.querySelector('.close-modal');
if (cdom && !cdom.contains(e.target)) {
rightVisible.value = false;
visibleTemp.value = 0;
}
} else {
visibleTemp.value = 1;
}
};
const requestFullScreen = () => {
const element = document.getElementsByClassName('right')[0];
if (fullscreen.value) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
} else {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
fullscreen.value = !fullscreen.value;
};
const pipelineStatus = (status) => {
switch (status) {
case 0:
return "5, 5";
case 1:
return "1, 5";
case 2:
return "15, 10, 5, 10";
default:
return "1";
}
};
const pipelineStatusSelected = (status) => {
switch (status) {
case 0:
return "10, 10";
case 1:
return "2, 10";
case 2:
return "30, 15, 10, 15";
default:
return "1";
}
};
const showDirection = (checked) => {
directionChecked.value = checked;
darwerPipeline();
};
const lineGroupClearAndInit = () => {
linesGroup.value.forEach((layer) => {
leafletMap.value.removeLayer(layer);
});
linesGroup.value = [];
linesDirectionGroup.value.forEach((layer) => {
leafletMap.value.removeLayer(layer);
});
lineList.value.forEach((line) => {
if (line.operation === 'edit') {
line.operation = '';
line.weight = 2;
}
});
if (currentPipelinetId.value) {
if (pipelinePosLen.value == 4) {
const index = pipelineIdList.value.indexOf(currentPipelinetId.value);
if (index !== -1) {
lineList.value[index].operation = 'edit';
lineList.value[index].weight = 6;
} else {
allLineList.value.forEach((item) => {
if (item.id === currentPipelinetId.value) {
item.operation = 'add';
lineList.value.push(item);
}
});
}
}
if (pipelinePosLen.value == 3) {
lineList.value.forEach((item) => {
if (item.superiorPipelineId == currentPipelinetId.value) {
item.operation = 'edit';
item.weight = 6;
}
});
阅读全文