Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ref, or watch, or similar functionalities in Vue Composition API

Tags:

vue.js

I want to know how can I use ref or watch in setup() area of Vue 3 when importing vue through a CDN.

Here's the code:

<div id="app">

    {{ counter }}

  </div>

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

This throws an error

ref is not defined

like image 833
kasrap Avatar asked Oct 12 '25 00:10

kasrap


1 Answers

To import ref try:

const { createApp, ref, computed, watch } = Vue;

You need to return variables from setup as object like this

const app = createApp({
  props: {
    name: String
  },
  setup(){
    const capacity = ref(3)
    return { capacity };
  },
  /* data(){  // NO NEED
    return {
      counter: 43
    }
  }, */
})
like image 135
ashwin bande Avatar answered Oct 14 '25 15:10

ashwin bande