vue是如何获取元素节点 ?

我心飞翔 分类:vue

Js中:用document.getElement之类的语句来操作dom;
vue:使用vue提供的api,用 ref 来获取节点;

首先先用ref在元素上面做一个标记,然后用this.$refs.标记名来获取元素

代码:

<!DOCTYPE html>
<html>
 
<head>
  <meta charset="utf-8">
  <title>document</title>
  <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
 
<body>
  <div id="app">
    <span ref='pTag'>{{ message }}</span>
  </div>
 
  <script>
    new Vue({
      el: '#app',
      data() {
        return {
          message: 'hello 肾虚少年'
        }
      },
      mounted() {
        alert(this.$refs.pTag.innerHTML)
      }
    })
  </script>
</body>
 
</html>

vue2.0 对比 vue10 获取元素:

vue1.0 :版本中

在标签中加上el=’dom’,然后在代码中this.$els.dom这样就拿到了页面元素

例如:<div class=’box’  v-el: myBox>你好</div>

让你好的颜色显示为红色:this.$els.my-box.style.color = ‘red’

vue2.0:版本中

在标签中加上 ref=’dom’,然后在代码中this.$refs.dom这样就拿到了页面元素

例如:<div class=’box’ ref=’myBox’>你好</div>

让你好的颜色显示为红色:this.$refs.myBox.style.color = ‘red

回复

我来回复
  • 暂无回复内容