在vue组件中访问屏幕宽度

Tan*_*may 3 javascript vue.js

目前我正在将window.innerWidth值存储到一个名为的 vuex getter 中screenWidth,并在我的所有组件中使用它。但问题是每次我想使用它时,我都必须 1) import { mapGetters } from 'vuex'2)...mapGetters()在计算属性内调用。为了摆脱这个问题,我认为原型注入可能是一个好主意。所以我这样做了:

Vue.prototype.$screenWidth = window.innerWidth;
window.addEventListener('resize', () => {
    Vue.prototype.$screenWidth = window.innerWidth;
});
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。如何在不执行所有导入/映射内容的情况下更轻松地访问组件中的屏幕宽度?

ski*_*tle 6

你已经用 Vuex 做到这一点的方式对我来说听起来不错。

如果您在很多组件中使用它,那么另一种选择可能是在原型上使用可观察对象,如下例所示。通过使用对象,我们可以保留反应性。

Vue.prototype.$screen = Vue.observable({
    width: window.innerWidth,
    height: window.innerHeight
});

window.addEventListener('resize', () => {
    Vue.prototype.$screen.width = window.innerWidth;
    Vue.prototype.$screen.height = window.innerHeight;
});

new Vue({
    el: '#app'
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<div id="app">
  <p>Width: {{ $screen.width }}</p>
  <p>Height: {{ $screen.height }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)

这个依赖于Vue.observable,需要Vue 2.6.0。在 Vue 的早期版本中,您可以通过创建临时 Vue 实例并将对象分配给该实例的数据来执行类似的操作:

Vue.prototype.$screen = new Vue({
    data: {
        screen: {
            width: window.innerWidth,
            height: window.innerHeight
        }
    }
}).screen;

window.addEventListener('resize', () => {
    Vue.prototype.$screen.width = window.innerWidth;
    Vue.prototype.$screen.height = window.innerHeight;
});

new Vue({
    el: '#app'
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.22/dist/vue.js"></script>
<div id="app">
  <p>Width: {{ $screen.width }}</p>
  <p>Height: {{ $screen.height }}</p>
</div>
Run Code Online (Sandbox Code Playgroud)

它看起来很可怕,但这就是Vue.observable引入的原因。

请注意,SO 将这些片段包装在 iframe 中,因此当您调整浏览器窗口大小时,您可能看不到数字更新。对我来说,我要么必须使窗口变得非常窄,要么单击展开片段链接才能看到它的工作原理。