How to use options API along with Composition API in vue3?

Viewed 1105

vue3 + vite2

Very simple code as below.
Expect: when click on button, change reactive msg variable.
it works expectly when development(vite), after build production(vite build) and deploy, it seem cannot work, click method cannot access reactive msg variable.
From vuejs document, options API can work along with composition API.

<template>
  <h1>{{ msg }}</h1>
  <button @click="click">Click</button>
</template>

<script setup>
  const msg = ref('hello')      
</script>

<script>
  import { ref } from 'vue'
  export default {   
    methods: {
      click() {
        this.msg = 'ok'     
      },
    },
  }
</script>
1 Answers

You can combine options and composition api if you use setup function:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const msg = ref('hello')
    return { msg }
  },
  methods: {
    click() {
      this.msg = 'ok'     
    },
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <h1>{{ msg }}</h1>
  <button @click="click">Click</button>
</div>

Related