美文网首页锤子前端
Vue获取动态样式的宽度;监听获取浏览器的高度和宽度

Vue获取动态样式的宽度;监听获取浏览器的高度和宽度

作者: 小棋子js | 来源:发表于2020-03-05 16:22 被阅读0次

一。用vue 获取动态元素的宽度。首页,要放在this.nextTick里面,其实要使用el挂载此元素,下面贴代码

<el-input auto-complete="off" v-model="company.companyName" ref="companyStyle"></el-input>
先定义一个ref=companyStyle,我们来获取此元素的宽度,

  newAddBtn(){
        let me = this;
        this.$nextTick(function () {
          me.inputStyWidth = me.$refs.companyStyle.$el.clientWidth + 'px';
        })

这样我们就获取到了这个元素的宽度了
二。监听获取浏览器的高度(另外宽度把clientHeight改为clientWidth)
vue组件中动态获取高度,使用如下方式
首先在data中声明clientHeight变量:

data() {
  return {
    clientHeight: '',
  }
},

如果需要在初始化有一些操作,可以在created中实现:

created() {
  this.windowHeight(document.documentElement.clientHeight);
},

当组件挂载后,调用JS的onresize方法:

mounted() {
  const _this = this;
  window.onresize = () => {
    return (() => {
      _this.clientHeight= `${document.documentElement.clientHeight}`;
    })();
  };
},

在watch中监听高度变化,这里优化了监听间隔,使用setTimeout,每500ms监听一次,这样操作避免了浏览器大小在持续变化时,连续监听带来的卡顿现象:

watch: {
  clientHeight(val) {
    if(!this.timer) {
      this.clientHeight= val
      this.timer = true
      let _this = this
      setTimeout(function () {
        _this.timer = false
      }, 500)
    }
    // 这里可以添加修改时的方法
    this.windowHeight(val);
  }
},

定义上面修改时具体的操作方法:

methods: {
  windowHeight(value) {
           this.clientHeight = value
      }
},

这样就可以实现监听浏览器大小的改变。

相关文章

网友评论

    本文标题:Vue获取动态样式的宽度;监听获取浏览器的高度和宽度

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