vue存在大量的異步加載問題,比如動態創建dom元素,若你緊接着去獲取創建的dom元素是獲取不到的。
解決辦法:
第一種辦法比較low,使用setTimeout方法,讓獲取dom的代碼在動態創建元素之後一段時間(這個時間非常的短)去執行。但這種方法應該是存在風險的,不推薦。
第二種辦法 在將要執行的代碼上套一層 this.$nextTick()
例如:
this.$nextTick(function() {
let grids = _that.$refs.datamessage;
console.log(grids);
for (let i = 0; i < grids.length; i++) {
let xb = grids[i].getAttribute("index");
//alert(xb);
if (_that.value.indexOf(xb) != -1) {
grids[i].setAttribute("ifSelect", "true");
grids[i].style.backgroundColor = "#b3d8ff";
grids[i].style.color = "#409eff";
}
}
});