1

我正在尝试使用加载功能制作一个简单的 Vuetify 按钮。Vuetify 已预制组件。我正在尝试将他们提供的代码转换为与组合 api 一起使用。

我遇到了问题this

这是 Vuetify 提供的:

<template>
  <div class="text-center">
    <v-btn
      class="ma-2"
      :loading="loading"
      :disabled="loading"
      color="secondary"
      @click="loader = 'loading'"
    >
      Accept Terms
    </v-btn>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        loader: null,
        loading: false,
      }
    },
    watch: {
      loader () {
        const l = this.loader
        this[l] = !this[l]

        setTimeout(() => (this[l] = false), 3000)

        this.loader = null
      },
    },
  }
</script>

<style>
  .custom-loader {
    animation: loader 1s infinite;
    display: flex;
  }
  @-moz-keyframes loader {
    from {
      transform: rotate(0);
    }
    to {
      transform: rotate(360deg);
    }
  }
  @-webkit-keyframes loader {
    from {
      transform: rotate(0);
    }
    to {
      transform: rotate(360deg);
    }
  }
  @-o-keyframes loader {
    from {
      transform: rotate(0);
    }
    to {
      transform: rotate(360deg);
    }
  }
  @keyframes loader {
    from {
      transform: rotate(0);
    }
    to {
      transform: rotate(360deg);
    }
  }
</style>

所以转换为组合 API,这就是我所在的位置。我的watch功能显然是非常错误的。不确定这是否是使用这个新的正确方法watch。另一个问题是如何处理this这种格式的情况:

import { ref, watch } from '@vue/composition-api'

setup () {
  let loader = ref(null)
  let loading = ref(false)

  watch( () => {
    loader () {
      const l = loader.value
      this[l] = !this[l]

      setTimeout(() => (this[l] = false), 3000)

      loader.value = null
    }
  })

  return {
    loader,
    loading,
  }
}
4

1 回答 1

1

对于 3.xwatch方法,第一个参数应该是您要观察的ref(或 s 的数组);ref第二个参数是处理程序/回调,它接收新值和旧值作为其参数(如2.x$watch中的回调所示)。

例如,要设置新ref值的记录器:

watch(myRef, (newValue, oldValue) => console.log(newValue))

// or
watch(myRef, () => console.log(myRef.value))

关于this:由于loader.value指的是其他refs 之一,您可以为回调ref使用的目标 s创建一个查找。watch在这个例子中,只有一个ref(但以后可以添加更多):

let loading = ref(false)

const refs = {
  loading
}

watch(myRef, () => {
  console.log(refs['loading'].value)
})

总而言之,使用 Composition API 的翻译代码如下所示:

import { ref, watch } from '@vue/composition-api'

export default {
  setup() {
    let loader = ref(null)
    let loading = ref(false)

    const refs = {
      loading
    }
    watch(loader, () => {
      const l = loader.value
      if (!l) return

      refs[l].value = !refs[l].value

      setTimeout(() => (refs[l].value = false), 3000)

      loader.value = null
    })

    return {
      loader,
      loading
    }
  }
}

演示

于 2020-07-17T07:57:22.987 回答