如何在 Vue Composition API 中使用 ref、watch 或类似功能

kas*_*rap 4 vue.js

我想知道通过 CDN 导入 vue 时如何在 Vue 3 的 setup() 区域中使用 ref 或 watch 。

这是代码:

<div id="app">

    {{ counter }}

  </div>

<script src="https://unpkg.com/vue@next"></script>
Run Code Online (Sandbox Code Playgroud)
const app = Vue.createApp({
  props: {
    name: String
  },
  setup(){
    const capacity = ref(3)
  },
  data(){
    return {
      counter: 43
    }
  },
})
Run Code Online (Sandbox Code Playgroud)

这会引发错误

参考未定义

ash*_*nde 6

要导入参考尝试:

const { createApp, ref, computed, watch } = Vue;
Run Code Online (Sandbox Code Playgroud)

setup您需要像这样从对象返回变量

const app = createApp({
  props: {
    name: String
  },
  setup(){
    const capacity = ref(3)
    return { capacity };
  },
  /* data(){  // NO NEED
    return {
      counter: 43
    }
  }, */
})
Run Code Online (Sandbox Code Playgroud)