vue.jsvuejs3tsx

ref lost its reactivity in tsx


import { ref } from 'vue'
const Test = () => {
  const msg = ref('I am Brave')
  const changeMsg = () => {
    console.log('aa')
    msg.value = 'I will get everything I want'
  }
  return (
    <div>
      <span>{msg.value}</span>
      <button onClick={changeMsg}>btn</button>
    </div>
  )
}

export default Test

when I click the button,the function changeMsg excuted, but the view did not change with the click operation

I want to make the view to change when I click the button


Solution

  • It's like script-setup syntax:

    import { ref, defineComponent } from 'vue'
    
    const Test = defineComponent({
        setup() {
            const msg = ref('I am Brave')
    
            const changeMsg = () => {
                console.log('aa')
                msg.value = 'I will get everything I want'
            } 
    
            return () => (
                <div>
                    <span>{msg.value}</span>
                    <button onClick={changeMsg}>btn</button>
                </div>
            );
        },
    });
    
    export default Test
    

    Update

    Or just wrap in defineComponent function, and return arrow function with jsx

    const Test = defineComponent(() => {
        const msg = ref('I am Brave')
    
        const changeMsg = () => {
          console.log('aa')
          msg.value = 'I will get everything I want'
        }
    
        return () => (
          <div>
            <span>{msg.value}</span>
            <button onClick={changeMsg}>btn</button>
          </div>
        )
    })