【问题标题】:Why does the this scope change when calling from a template or watcher?为什么从模板或观察者调用时 this 范围会发生变化?
【发布时间】: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

始终发送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 的新手,并试图了解正在发生的事情。感谢您就如何最好地处理此类情况提供帮助和/或建议。

【问题讨论】:

    标签: javascript vue.js vue-component vue-composition-api


    【解决方案1】:

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

    试试这个:

    watch(() => this.$q.screen.width, setMiniState)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多