0

在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>

模板化组合 API 组件的检查组件

非模板“渲染”组件:

<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>

非模板化组合 API 组件的已检查组件

使用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>

带渲染的已检查选项 API 组件

4

1 回答 1

0

我不能说这是正确的方法,因为它看起来很老套而且不是很理想,但它确实做了我现在需要做的事情。此解决方案使用provide方法,该方法授予对通过componentInstance._provided提供的属性/方法的访问权限。不过,这样做并不是很欣喜若狂:

<script lang="ts">
import { defineComponent, Ref, ref, createElement, provide, computed } from '@vue/composition-api'
export default defineComponent({
  name: 'TranslationSidebar',
  setup () {
    const counter: Ref<number> = ref(0)
    const increment = () => {
      counter.value++
    }
    provide('increment', increment)
    provide('counter', computed(() => counter.value))
    return () => {
      return createElement('div', { on: { click: increment } }, String(counter.value))
    }
  }
})
</script>

在此处输入图像描述

于 2020-07-27T14:04:16.333 回答