1

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 Answer 1

8

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>

4
  • So basically whatever the setup function returns acts like what we used to return in data() in Vue 2.x?
    – connexo
    Mar 30, 2022 at 10:42
  • 1
    @connexo Not just data() you also have to return methods from setup() or use <script setup> in Single File Components.
    – AndreKR
    Aug 23, 2022 at 0:24
  • how can you call click() from the setup section?
    – mga
    Sep 8 at 18:15
  • 1
    @mga hey mate, You can not , it is one way road, so You can only use data function properties, computed , methods from options api, not other way around Sep 8 at 18:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.