0

关于我之前包含所有代码的问题,我想知道为什么它可以正常工作:

<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

始终发送statewidth参数:

<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 的新手,并试图了解正在发生的事情。感谢您对如何最好地处理这种情况的帮助和/或建议。

4

1 回答 1

0

你为什么写作'$q.screen.width'

尝试这个:

watch(() => this.$q.screen.width, setMiniState)
于 2020-05-11T08:35:24.913 回答