关于我之前包含所有代码的问题,我想知道为什么它可以正常工作:
<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
setMiniState
如果参数width
可用,请签入函数:
<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 的新手,并试图了解正在发生的事情。感谢您对如何最好地处理这种情况的帮助和/或建议。