vue中的异步问题困扰了好久,终于解决了,mark一下给需要的朋友。
项目开始使用vuex来解决组件之间变量传值的问题。但是用着用着出现了一个问题,子组件中用到mapboxMap属性,而mapboxMap属性值需要等待父组件初始化函数执行完之后才会有,这就存在一个异步的问题,页面已初始化加载的时候mapboxMap是为undefined,解决方法为在子组件中监听mapboxMap的值,具体方法如下:
父组件中:
this.$store.commit('SET_MAPBOXMAP', mapboxMap)
子组件中
- 首先,采用计算属性来获取$store中的值
- 其次,watch来监听计算属性获取到的值的变化
<script>
import { mapGetters } from 'vuex'
export default {
name: "mapbox-layer",
render() {
return "";
},
data: () => ({
}),
props: {
layerData: {
type: String,
default: ""
}
},
computed: {
...mapGetters(["mapboxMap"]),
mapboxMap1() {
// return this.$store.state.mapbox.map;
return this.mapboxMap;
}
},
watch: {
mapboxMap1(newData, oldData) {
console.dir("watch")
if (!newData) return "";
this.reload();
},
layerData(newData, oldData) {}
},
methods: {
reload() {
// let gdData = require(`static/json/${this.layerData}`)
let gdData = this.layerData;
let mapboxMap = window.mapboxMap;
mapboxMap.on("load", function() {
mapboxMap.addSource("states", {
type: "geojson",
data: gdData
});
mapboxMap.addLayer({
id: "state-fills",
type: "fill",
source: "states",
layout: {},
paint: {
"fill-color": "#627BC1",
"fill-opacity": 0.1
}
});
mapboxMap.addLayer({
id: "state-borders",
type: "line",
source: "states",
layout: {},
paint: {
"line-color": "#fff",
"line-width": 2
}
});
mapboxMap.addLayer({
id: "state-fills-hover",
type: "fill",
source: "states",
layout: {},
paint: {
"fill-color": "orange",
"fill-opacity": 0.3
},
filter: ["==", "name", ""]
});
});
}
}
};
</script>