【发布时间】:2020-08-22 15:07:30
【问题描述】:
关于包含所有代码的previous question,我想知道为什么它可以正常工作:
<template>
<q-drawer
@mouseover="setMiniState(false)"
@mouseout="setMiniState(true)"
</template>
<script>
import { defineComponent, ref, watch } from '@vue/composition-api'
export default defineComponent({
setup() {
const miniState = ref(true)
function setMiniState(state) {
console.log('setMiniState widht is ', this.$q.screen.width)
}
return {
miniState, setMiniState
}
}
})
但这不是:
function setMiniState(state) {
console.log('setMiniState widht is ', this.$q.screen.width)
}
watch('$q.screen.width', () => setMiniState())
当观察者被调用时,变量$q变成undefined,当从模板调用相同的函数时,情况就不是这样了。似乎this 作用域正在改变setMiniState 函数的调用方式。
解决方法 1
如果参数width 可用,请检查函数setMiniState:
<template>
<q-drawer
@mouseover="setMiniState(false)"
@mouseout="setMiniState(true)"
</template>
function setMiniState(state, width) {
let screenWidth = ''
if (!width) {
screenWidth = this.$q.screen.width
} else {
screenWidth = width
}
console.log('setMiniState this is ', screenWidth)
}
watch('$q.screen.width', (width) => setMiniState(undefined, width))
解决方法 2
始终发送state 和width 参数:
<template>
<q-drawer
@mouseover="setMiniState(false, $q.screen.width)"
@mouseout="setMiniState(true, $q.screen.width)"
</template>
function setMiniState(state, width) {
console.log('setMiniState this is ', width)
}
watch('$q.screen.width', (width) => setMiniState(undefined, width))
我是 javaScript 的新手,并试图了解正在发生的事情。感谢您就如何最好地处理此类情况提供帮助和/或建议。
【问题讨论】:
标签: javascript vue.js vue-component vue-composition-api