Vue 3 - 如何在没有 .value 的情况下使用反应式引用和计算?

Vue 3 - How to use reactive ref and computed without .value?

当我们使用Options API时,我们可以在computed部分定义一些属性,在data部分定义一些属性。所有这些都可以通过 this 引用从实例访问,即在同一个对象中。很合适

例如:

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

其中 hasMore 是计算的 属性,loading 是反应的 属性。

是否有可能通过 Composition API 做类似的事情?例如,要实现类似的代码,但是 pagination 是一个简单的对象,而不是组件的 link,例如:

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

computed 根本不是解决方案,因为它 returns ref 和它的使用将与上面示例中 this 的使用完全不同。

您可以使用具有 属性 的 reactive 对象,这是一个计算对象。然后一切都可以按照您想要的方式访问:

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

演示:

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://unpkg.com/vue@next"></script>

如果您真的不喜欢将 .value 与 ref 一起使用,您可能会对提议的 Reactivity Transform 提案感兴趣,该提案将允许您在不使用 .value 的情况下使用 ref。关注这里的讨论:https://github.com/vuejs/rfcs/discussions/369

// 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 vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue({ reactivityTransform: true })]
})