作为vue的面试题,Vue操作dom元素的方法有哪些,可能是随口一问的问题。

vue中有3种方式操作dom元素。

  1. 原生js操作dom
  2. 使用vue ref操作dom
  3. 使用jquery操作dom

下面给出3种方式的例子

<template>
  <div>
    <p id="intro1">原生js操作dom:</p>
    <button  @click="jsUpdateDom">原生js修改颜色</button>

    <p ref="intro2">vue ref 修改dom元素:</p>
    <button @click="refUpdateDom">ref修改颜色</button>

    <p id="intro3">jquery 修改dom元素:</p>
    <button  @click="jqueryUpdateDom">jquery修改颜色</button>

  </div>
</template>

<script>
import $ from 'jquery'
export default {
  name: "HomeIndex.vue",
  methods:{
    //原生js
    jsUpdateDom:function (){
      const intro1 = document.getElementById("intro1")
      intro1.style.color = "red"
    },
    //ref
    refUpdateDom:function (){
      this.$refs.intro2.style.color = "green"
    },
    //jquery
    jqueryUpdateDom:function (){
      console.log("jquery 修改文字颜色");
      $("#intro3").css("color","blue");
    },
  }
}
</script>

<style scoped>

</style>
输出:

Vue操作dom元素的方法有哪些

在vue不建议使用jquery的方式操作dom元素,因为jquery操作dom的方法是通过循环页面找到所有符合的元素,而vue是单页面的。