目前,我将 window.innerWidth
值存储到名为 screenWidth
的 vuex getter 中,并在我的所有组件中使用它。但问题是每次我想使用它时,我都必须 1) import { mapGetters } from 'vuex'
2) 在计算中调用 ...mapGetters()
属性(property)。为了摆脱这个问题,我认为原型(prototype)注入(inject)可能是一个好主意。所以我这样做了:
Vue.prototype.$screenWidth = window.innerWidth;
window.addEventListener('resize', () => {
Vue.prototype.$screenWidth = window.innerWidth;
});
但这行不通。如何在不执行所有导入/映射内容的情况下更轻松地访问组件中的屏幕宽度?
最佳答案
你已经使用 Vuex 实现的方式对我来说听起来不错。
如果您在很多组件中使用它,那么也许另一种选择是在原型(prototype)上使用可观察对象,如下例所示。通过使用对象,我们可以保留 react 性。
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'
});
<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>
这依赖于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'
});
<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>
它看起来很可怕,但这就是引入 Vue.observable
的原因。
请注意,SO 将这些片段包装在 iframe 中,因此当您调整浏览器窗口大小时,您可能看不到数字更新。对我来说,我要么必须使窗口变得非常窄,要么单击展开代码段链接才能看到它的工作原理。
关于javascript - 在vue组件中访问屏幕宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56595804/