在Vue.js中使用“渲染”函数(而不是模板)时,有没有办法使用Composition API绑定(并在组件本身中公开)“数据”/“方法”?
(之前在 Options API 中,如果在 options 配置中使用render方法,所有的data/props/methods仍然暴露在组件本身,仍然可以通过componentInstance.someDataOrSomeMethod访问)
模板化组件:
<template>
<div @click="increment">{{ counter }}</div>
</template>
<script lang="ts">
import { defineComponent, Ref, ref, computed } from '@vue/composition-api'
export default defineComponent({
name: 'TranslationSidebar',
setup () {
const counter: Ref<number> = ref(0)
const increment = () => {
counter.value++
}
return {
counter: computed(() => counter.value),
increment
} // THIS PROPERTY AND METHOD WILL BE EXPOSED IN THE COMPONENT ITSELF
}
})
</script>
非模板“渲染”组件:
<script lang="ts">
import { defineComponent, Ref, ref, createElement } from '@vue/composition-api'
export default defineComponent({
name: 'TranslationSidebar',
setup () {
const counter: Ref<number> = ref(0)
const increment = () => {
counter.value++
}
return () => {
return createElement('div', { on: { click: increment } }, String(counter.value))
} // THE COUNTER PROP AND INCREMENT ARE BOUND, BUT NOT EXPOSED IN THE COMPONENT ITSELF
}
})
</script>
使用render选项的选项 API :
<script lang="ts">
export default {
name: 'Test',
data () {
return {
counter: 0
}
},
mounted () {
console.log('this', this)
},
methods: {
increment () {
this.counter++
}
},
render (h) {
return h('div', { on: { click: this.increment } }, this.counter)
}
}
</script>