改变这种参考VUE实例

问题描述 投票:0回答:1

我想有机会获得一个VUE例如在一个外部函数(防抖)。然而,这引导到窗口对象。我怎样才能改变的背景下?在这所指向的对象“窗口”的那一刻,我只想去VUE“数据”

这是我的榜样

jsfiddle

var debounce = function(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

new Vue({
  el: "#app",
  data: {
    media: 'phone'
  },
  methods: {
  	resizeMedia: debounce((e) => {
    						console.log('resize debounce');
              
    						//here vue this?
                this.media = window
                .getComputedStyle(
                document.querySelector('#app'), ':before')
                               .getPropertyValue('content')
                               .replace(/\"/g, '');
                
    },250),
  },
  mounted: function () {
      window.addEventListener('resize',  this.resizeMedia)
  },
  beforeDestroy: function () {
      window.removeEventListener('resize', this.resizeMedia)
  },
})
body {
  background: #ccc;
  padding: 20px;
}
body:before {
      content: "small-phone";
}
@media (min-width: 200px) {
    body:before {
      content: "phone";
    }
}
@media (min-width: 300px) {
    body:before {
      content: "tablet";
    }
}
@media (min-width: 400px) {
    body:before {
      content: "desktop";
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ media }}
</div>
javascript vue.js this debounce
1个回答
2
投票

的溶液将是,使用一个“正常”的功能,而不是箭头函数,如下所示:

resizeMedia: debounce(function() {
  // logs the vue instance
  console.log(this);               
 }, 250),
},
© www.soinside.com 2019 - 2024. All rights reserved.