Subscribe on changes!

why props slots and attrs are not same in render and setup funcion? what's the best practice to use they?

avatar
May 28th 2021

Version

3.1.0-beta.5

Reproduction link

https://codesandbox.io/s/pensive-glitter-s2wmu?file=/src/App.vue

Steps to reproduce

YouHead.jsx

import { ref } from 'vue'
export default {
  name: 'YouHead',
  inheritAttrs: false,
  props: ['h'],
  setup(props, { slots, emit, attrs }) {
    console.log('setup props')
    console.log(props)
    console.log('setup slots')
    console.log(slots) // is real slots
    console.log('setup attrs')
    console.log(attrs) // contains event and props
    const person = ref({ name: 'jack', age: 23 })
    const tech = ref('vue')

    return {
      // tech,
      person,
      // slots,
      emit,
    }
  },
  render(props, slots, attrs, vnode) {
    console.log('props')
    console.log(props) // not props
    console.log('slots')
    console.log(slots) // [] not slots
    console.log('attrs')
    console.log(attrs) // { h:1}
    console.log('vnode')
    console.log(vnode)
    const handlerClick = () => {
      this.emit('my-click', this.person.age)
    }
    const button = <button onClick={handlerClick}>button</button>
    const children = [button]
    return <h1>{children}</h1>
  },
}

parent com:

<template>
  <div>
    <YouHead :h="1" @my-click="onMyClick">
      <template #default>
        <span>default slot {{ dataFromChild }}</span>
      </template>
    </YouHead>
  </div>
</template>

<script>
import { ref } from 'vue'
import YouHead from './components/YouHead.jsx'
export default {
  name: 'App',
  components: { YouHead },
  setup() {
    const dataFromChild = ref(Math.random().toString(36))
    const onMyClick = data => {
      console.log('my-click', data)
    }
    return {
      dataFromChild,
      onMyClick,
    }
  },
}
</script>

What is expected?

Hope they behave same in tow functions.

What is actually happening?

They are not same.


It is very confusing. we can use render and setup to generate vnode. what it is the best parctice?

avatar
May 28th 2021

Manual render function should use this.$slots, this.$attrs etc. The arguments are for compiler-generated render functions only.