如何在 vue3 中使用选项 API 和组合 API?

tgf*_*gf2 1 javascript vue.js vuejs3

vue3+vite2

非常简单的代码如下。
预期:当单击按钮时,更改反应性消息变量。
它在开发(vite)时按预期工作,在构建生产(vite build)和部署后,它似乎无法工作,单击方法无法访问反应式消息变量。
从 vuejs 文档来看,选项 API 可以与组合 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>
Run Code Online (Sandbox Code Playgroud)

Nik*_*vic 10

如果您从设置函数返回值、方法,则可以组合选项和组合 api:

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')
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)