vue中的異步問題困擾了好久,終于解決了,mark一下給需要的朋友。
項目開始使用vuex來解決組件之間變量傳值的問題。但是用著用著出現(xiàn)了一個問題,子組件中用到mapboxMap屬性,而mapboxMap屬性值需要等待父組件初始化函數(shù)執(zhí)行完之后才會有,這就存在一個異步的問題,頁面已初始化加載的時候mapboxMap是為undefined,解決方法為在子組件中監(jiān)聽mapboxMap的值,具體方法如下:
父組件中:
this.$store.commit('SET_MAPBOXMAP', mapboxMap)
子組件中
- 首先,采用計算屬性來獲取$store中的值
- 其次,watch來監(jiān)聽計算屬性獲取到的值的變化
<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>