为什么在Vue Composition API设置功能中未定义“ this”?

时间:2020-07-22 13:38:26

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

我有一个使用v3的composition API的Vue组件:

<template>
  <input type="checkbox" v-model="playing" id="playing" @input="$emit('play', $event.target.value)" />
  <label for="playing" >{{ playing ? 'Pause' : 'Play' }}</label>
</template>
<script>
export default {
  props: {
    done: Boolean
  },
  setup(props) {
    const playing = ref(true)
    watchEvent(() => {
      if (props.done) {
        playing.value = false
        this.$emit('play', playing.value)
      }
    }
    return { playing }
  }
}
</script>

当watchEvent运行时,出现错误Cannot read property "$emit" of undefined。看来我使用的是错误类型的函数(箭头与普通函数)。

this似乎在setup()中都是未定义的,无论它是函数还是箭头函数。

1 个答案:

答案 0 :(得分:2)

setup function in the Vue Composition API接受两个参数:props和context。

第二个参数提供了一个上下文对象,该对象公开了先前在2.x API中公开的属性的选择性列表:

const MyComponent = {
  setup(props, context) {
    context.attrs // Previously this.$attrs
    context.slots // Previously this.$slots
    context.emit // Previously this.$emit
  }
}

重要的是要注意,破坏道具是不可行的(您会失去反应性),但是可以破坏上下文。

因此问题中的代码示例使用setup(props, { emit }),然后将this.$emit替换为emit