tgf2
tgf2

Reputation: 143

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

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>

Upvotes: 3

Views: 7926

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23500

You can combine options and composition api if you return values, methods from setup function:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const msg = ref('hello')
    const changeMsg = () => {
      return 'again'
    }
    return { msg, changeMsg }
  },
  data() {
    return {
      otherMsg: this.changeMsg()
    }
  },
  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>
  <h1>{{ otherMsg }}</h1>
  <button @click="click">Click</button>
</div>

Upvotes: 10

Related Questions