Search code examples
jsxvuejs3vue-functional-component

Why ref is not working in vue3 jsx functional components?


As shown in the following code, it's not working. If I put the code on (1) outside of the function, it works. Why? Or any solutions?

// vue3.2 jsx functinal components

import { ref } from 'vue'

// const count = ref(0) // (2) it works here

export default function Counter() {
  const count = ref(0) // (1) not working here
  return (
    <>
      <div>count: {count.value}</div>
      <button
        onClick={() => {
          count.value++
        }}
      >
        add
      </button>
    </>
  )
}

Solution

  • You can change a little,use defineComponent wrapper Counter.

    refer: Composition API in a functional component

    import { ref } from 'vue'
    
    // const count = ref(0) // (2) it works here
    
    function Counter() {
      const count = ref(0) // (1) not working here
      return () => (
        <>
          <div>count: {count.value}</div>
          <button
            onClick={() => {
              count.value++
            }}
          >
            add
          </button>
        </>
      )
    }
    
    export default defineComponent(Counter);