我在Vue的计算属性中编写的matchMedia函数有一些问题。问题是当我加载/刷新页面时,该函数无法工作。只有当我在浏览器中在响应设计模式下调整屏幕大小后,它才能恢复工作。
这里是我的app.js代码
computed: {
widthChange() {
if (matchMedia) {
var mqT = window.matchMedia(" (max-width: 850px) and (min-width: 600px) ")
function changeWidthT(mqT) {
const sectionRight = document.querySelector(".section-right")
if (mqT.matches) {
sectionRight.classList.remove("col-7")
}
else {
sectionRight.classList.add("col-7")
}
}
mqT.addListener(changeWidthT)
}
}
},,我在页面的父页面中调用计算的属性。
<div class="frontpage-parent" :class="widthChange">...
</div>发布于 2019-10-30 13:52:53
您是否尝试过在挂载钩子中调用widthChange()以使其在加载时运行?
编辑尝试将const tst = this.widthChange;放置在mousnted钩子中
发布于 2019-10-30 14:10:12
您在这里滥用computed属性。它们应该是getter,这意味着它们只返回准备起诉值。你实际上是在那里附加事件侦听器。
相反,您需要使用数据属性并在挂载钩子中初始化侦听器:
export default {
name: 'Blah',
data () {
const tabletViewQuery = matchMedia('...')
return {
tabletViewQuery: tabletViewQuery.
tabletView: tableViewQuery.matches,
}
},
mounted () {
this.tabletViewQuery.addListener(() => {
this.tabletView = tableViewQuery.matches
}
}
}然后用在桌子上:
<div class="section-right" :class="{ 'col-7': tabletView }">然而,可能更清洁的解决方案是使用vue-匹配媒体插件。
发布于 2022-06-03 10:56:45
活性Vue中的matchMedia
上述的答案对我没有用。改进BroiSatse的答案,将被废弃的addListener替换为change事件,就像https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList上提到的
带有类型记录示例的Vue Options API:
data(): { mediaQuery: MediaQueryList; isTablet: boolean; } {
const mediaQuery = window.matchMedia('(max-width: 1024px)');
return {
mediaQuery,
isTablet: mediaQuery.matches
};
},
mounted(): void {
this.mediaQuery.addEventListener('change', () => {
this.isTablet = this.mediaQuery.matches;
});
}https://stackoverflow.com/questions/58626873
复制相似问题