3

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

10

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>

Sign up to request clarification or add additional context in comments.

4 Comments

So basically whatever the setup function returns acts like what we used to return in data() in Vue 2.x?
@connexo Not just data() you also have to return methods from setup() or use <script setup> in Single File Components.
how can you call click() from the setup section?
@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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.