Ted*_*rin 4 javascript vue.js vuejs3 vue-composition-api
我有一个使用 v3 的组合 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>
Run Code Online (Sandbox Code Playgroud)
当 watchEvent 运行时,我收到错误 Cannot read property "$emit" of undefined。看起来我没有使用错误类型的函数(箭头与普通函数)。
无论是函数还是箭头函数,似乎this始终未定义setup()。
Vue Composition API 中的setup 函数接收两个参数: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
}
}
Run Code Online (Sandbox Code Playgroud)
重要的是要注意,解构 props 是不行的(你会失去反应性),但解构上下文是可以的。
所以问题中的代码示例,使用setup(props, { emit })然后替换this.$emit为emit.