美文网首页
Vue 中获取 DOM 元素问题

Vue 中获取 DOM 元素问题

作者: 昵称啦啦啦 | 来源:发表于2018-12-02 15:32 被阅读0次

Vue 获取DOM元素

获取元素

template 部分

<!-- 用ref属性来命名 -->
<button ref="btn">我是按钮</button>

js 部分

// 在 mounted 里面获取
mounted () {
  // 装载之后 此处可以操作dom
  console.log(this.$refs.btn); 
}

给元素添加事件 需要用到$nextTick

template 部分

<div>
  <input ref="input" type="text" v-if="isShow"/> 
</div>

js 部分

data () {
  return {
    isShow: false
  }
},
mounted () {
  // 装载之后 此处可以操作dom
  // 显示元素并获取焦点
  this.isShow = true;
  this.isShow = false;
  this.isShow = true;
  // 最终代码执行完毕后 vue才会根据实际的值,进行DOM的操作
  // this.$refs.input.focus(); // 无法执行
  // 我们希望在vue真正渲染DOM到页面以后才做的事
  this.$nextTick(function () {
    this.$refs.input.focus(); 
  })
}

相关文章

网友评论

      本文标题:Vue 中获取 DOM 元素问题

      本文链接:https://www.haomeiwen.com/subject/vzvjcqtx.html