20

When we use Options API, we can define some properties in the computed section and some properties in the data section. All of them become accessible from the instance through the this reference, i.e. in the same object. It's very suitable.

For example:

if (this.hasMore) {
   this.loading = true;
   ...
}

Where hasMore is a computed property, loading is a reactive property.

Is there any possibility to do something similar via Composition API? For example, to implement similar code, but where pagination is a simple object, not a link to a component, like:

if (pagination.hasMore) {
   pagination.loading = true;
   ...
}

The computed is not solution at all, because it returns ref and its using will be completely different than using of this in the example above.

0

2 Answers 2

12

You could use a reactive object having a property which is a computed. Then it will all be accessible the way you want:

const pagination = reactive({
  loading: false,
  hasMore: computed(() => {
    return true;
  })
})

Demo:

const { createApp, reactive, computed } = Vue;
const app = createApp({
  setup() {
    const pagination = reactive({
      loading: false,
      hasMore: computed(() => {
        return true;
      })
    })
    if (pagination.hasMore) {
      pagination.loading = true;
      // ...
    }
    return {
      pagination
    }
  }
});
app.mount("#app");
<div id="app">
  {{ pagination }}
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.7/vue.global.min.js"></script>

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

Comments

9

If you really dislike having to use .value with ref you might be interested in the Reactivity Transform compiler macro.

Update for 2023: Reactivity Transform feature will not be added to Vue 3 as a core feature. Instead, add the feature using the Vue Macros library. https://vue-macros.sxzz.moe/features/reactivity-transform.html

// declaring a reactive variable backed by an underlying ref
let count = $ref(1)
console.log(count); //no .value needed!

vite.config.js

import { defineConfig } from 'vite'
import ReactivityTransform from '@vue-macros/reactivity-transform/vite'

export default defineConfig({
  plugins: [ReactivityTransform()],
})

1 Comment

Thanks for the answer! Hope one day Vue will get rid of this annoying .value suffixes and follows Svelte neat approach.

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.