vue中获取并操作dom元素

获取dom元素可以使用

elementList = document.querySelectorAll(selectors);//获取多个dom元素 如ul中的li
element = document.querySelector(selectors)//获取dom元素中的第一个元素

在vue中使用

mounted(){//这里必须是mouted钩子
this.title = document.querySelector('#footer-box-title');
this.title.style.color = "#ff0000";
}

要在mounted中使用,因为只有在执行mounted的时候,vue已经渲染了dom节点,这个时候是可以获取dom节点的,vue中尽量不去操作dom元素,选用ref操作属性获取

<button ref="btn">获取ref</button>

this.$refs.btn.style.backgroundColor="#ff0000"

猜你喜欢

转载自blog.csdn.net/qq_35775675/article/details/80850553