0

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>
    </>
  )
}
MurphyChen
  • 57
  • 4

2 Answers2

2

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);
Heng
  • 52
  • 1
1

This is how Functional Components work - the function is called every time the component is rendered. Which means the new count ref is created each time a component is rendered (it is a local variable)

Functional components are an alternative form of component that don't have any state of their own.

There is no solution for that. If you need local state, do not use functional component.

Moving ref creation to module scope (2) is not solution either as it will lead to a single counter shared between all usages of your component

Michal Levý
  • 33,064
  • 4
  • 68
  • 86