101

看一些人对 Vue 3 的预览教程的一些例子。[目前正在测试中]

我找到了两个例子:

反应性

<template>
  <button @click="increment">
    Count is: {{ state.count }}, double is: {{ state.double }}
  </button>
</template>

<script>
import { reactive, computed } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0,
      double: computed(() => state.count * 2)
    })

    function increment() {
      state.count++
    }

    return {
      state,
      increment
    }
  }
}
</script>

参考

<template>
  <div>
    <h2 ref="titleRef">{{ formattedMoney }}</h2>
    <input v-model="delta" type="number">
    <button @click="add">Add</button>
  </div>
</template>

<script>
import { ref, computed, onMounted } from "vue";

export default {
  setup(props) {
    // State
    const money = ref(1);
    const delta = ref(1);

    // Refs
    const titleRef = ref(null);

    // Computed props
    const formattedMoney = computed(() => money.value.toFixed(2));

    // Hooks
    onMounted(() => {
      console.log("titleRef", titleRef.value);
    });

    // Methods
    const add = () => (money.value += Number(delta.value));

    return {
      delta,
      money,
      titleRef,
      formattedMoney,
      add
    };
  }
};
</script>
4

6 回答 6

201

关键点

  • reactive()只接受对象,而不接受JS 原语(String、Boolean、Number、BigInt、Symbol、null、undefined)
  • ref()reactive()在幕后呼唤
  • 由于reactive()适用于对象和ref()调用reactive(),因此对象适用于两者
  • 但是,ref()有一个.value重新分配的属性,reactive()没有这个,因此不能重新分配

采用

ref()什么时候..

  • 它是一个原始的(例如'string', true, 23, 等)
  • 这是您需要稍后重新分配的对象(如数组 -更多信息在这里

reactive()什么时候..

  • 这是一个您不需要重新分配的对象,并且您希望避免ref()

总之

ref()似乎是要走的路,因为它支持所有对象类型并允许重新分配.value. ref()是一个很好的起点,但是当您习惯了 API 时,就会知道它reactive()的开销更少,并且您可能会发现它更能满足您的需求。

ref()用例

您将始终使用ref()原语,但ref()适用于需要重新分配的对象,例如数组。

setup() {
    const blogPosts = ref([]);
    return { blogPosts };
}
getBlogPosts() {
    this.blogPosts.value = await fetchBlogPosts();
}

上面的 withreactive()需要重新分配一个属性而不是整个对象。

setup() {
    const blog = reactive({ posts: [] });
    return { blog };
}
getBlogPosts() {
    this.blog.posts = await fetchBlogPosts();
}

reactive()用例

一个很好的用例reactive()是一组属于一起的原语:

const person = reactive({
  name: 'Albert',
  age: 30,
  isNinja: true,
});

上面的代码感觉比

const name = ref('Albert');
const age = ref(30);
const isNinja = ref(true);

有用的链接

如果您仍然迷路,这个简单的指南帮助了我:https ://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/

仅使用的论点ref()https ://dev.to/ycmjason/thought-on-vue-3-composition-api-reactive-considered-harmful-j8c

Vue Composition API RFC背后的决策reactive()ref()其他重要信息:https ://vue-composition-api-rfc.netlify.app/#overhead-of-introducing-refs

于 2020-12-12T07:39:19.040 回答
21

ref和之间有一些相似之处reactive,因为它们都提供了一种存储数据的方法并允许该数据具有反应性。

然而:

高层差异:

你不能在原语(字符串、数字、布尔值)上使用 reactive() - 这就是你需要 refs 的地方,因为你会遇到需要“反应性布尔值”的情况,例如……</p>

当然,您可以创建一个包装原始值的对象并使其成为响应式():

const wrappedBoolean = reactive({
  value: true
})

就这样,你重新发明了一个裁判。

来源:Vue 论坛讨论

反应性

reactive获取对象并返回proxy对原始对象的反应。

例子

import {ref, reactive} from "vue";

export default {
  name: "component",
  setup() {
    const title = ref("my cool title")
    const page = reactive({
      contents: "meh?",
      number: 1,
      ads: [{ source: "google" }],
      filteredAds: computed(() => {
        return ads.filter(ad => ad.source === "google")
      })
    })
    
    return {
       page, 
       title
    }
  }
}

解释

在上面,每当我们想要更改或访问 的属性时,page都会通过代理进行更新。
page.adspage.filteredAds

于 2020-04-27T06:09:35.470 回答
3

ref / reactive 两者都用于创建跟踪更改的反应对象。

参考:

它接受一个原始参数并返回一个反应式可变对象。该对象具有单个属性“值”,它将指向它所采用的参数。

反应性:

它接受一个 JavaScript 对象作为参数,并返回该对象的基于 Proxy 的响应式副本。

参考与反应性:

通常,ref 和 reactive 都被用于创建响应式对象,其中 ref 用于使原始值成为响应式(布尔值、数字、字符串)。但是响应式不适用于原语,而不适用于对象。

有关更多详细信息:请参阅Ref vs Reactive

于 2020-12-18T07:05:21.043 回答
3

我将简单解释为什么有两种创建反应状态的方法:

其他答案已经显示了两者之间的差异


reactive:创建反应状态。返回对象的反应式代理:

import { reactive } from 'vue'

const reactiveObj = reactive({ count: 0 })
reactiveObj.count++

使用 Options API,我们曾经将反应状态保持在data(). 使用 Composition API,我们可以使用reactiveAPI 实现相同的目的。到目前为止,一切都很好,但是...

为什么我们需要ref???

仅仅因为reactive有以下限制:

  • 反应性损失:
const state = reactive({ count: 0 })

// the function receives a plain number and
// won't be able to track changes to state.count
callSomeFunction(state.count)
const state = reactive({ count: 0 })
let { count } = state
// does not affect original state
count++
let state = reactive({ count: 0 })

// this won't work!
state = reactive({ count: 1 })
  • 它不能保存原始类型,例如字符串、数字或布尔值。

因此ref,由 Vue 提供以解决reactive.

ref()接受参数并将其返回包装在具有 .value 属性的 ref 对象中:

const count = ref(0)

console.log(count) // { value: 0 }
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

裁判可以:

  • 持有任何值类型
  • 被动地替换整个对象:
const objectRef = ref({ count: 0 })

// this works reactively
objectRef.value = { count: 1 }
  • 传递给函数或从普通对象中解构而不会失去反应性
const obj = {
  foo: ref(1),
  bar: ref(2)
}

// the function receives a ref
// it needs to access the value via .value but it
// will retain the reactivity connection
callSomeFunction(obj.foo)

// still reactive
const { foo, bar } = obj

我应该一直使用ref吗?

个人意见如下

大多数尝试过这两种方法的开发人员都建议使用ref我读过的文章。

但就我个人而言,我认为这与使用不正确ref有相同的限制reactive,您很容易陷入“反应性损失”问题。 ref还有一些行为,如:

  • 在模板中展开,但这只发生在顶级属性中
  • 展开里面reactive
  • 当从数组或本地集合类型(如 Map)访问 ref 时,不执行展开
  • refs 的同步

.value每次都必须处理也有点令人困惑,Vue 知道这一点,并且在撰写本文时有一个RFC - Reactivity Transform旨在提供解决方案。

我希望您现在对这些有更好的理解,reactiveref我认为值得一提的是,您应该了解更多用于响应式状态的 API:readonly、shallowRef、shallowReactive、shallowReadonly、unref 等等。

于 2022-01-29T17:18:52.003 回答
1

Ref :它接受一个原始参数并返回一个反应式可变对象。该对象具有单个属性“值”,它将指向它所采用的参数。

Reactive :它将 JavaScript 对象作为参数,并返回该对象的基于代理的响应式副本。

您可以从这个视频教程中了解更多信息: https ://www.youtube.com/watch?v=JJM7yCHLMu4

于 2020-12-24T07:20:21.427 回答
0

您可以在下面看到我们在上半部分使用 Reactive References 的示例,以及在其他替代响应式语法下方。

//reactivity with ref syntax

import { ref, computed } from vue

export default {
  setup() {
    const capacity = ref(4)
    const members = ref(["Tim", "John", "Andr"])
    const simpleComputed = computed(() => {
      return capacity.value - members.value.length
    })

    return { capacity, members, simpleComputed }
  }
}


//reactivity with reactive syntax

import { reactive, computed } from vue

export default {
  setup() {
    const event = reactive({
      capacity: 4,
      members: ["Tim", "John", "Andr"]
      simpleComputed: computed(() => {
        return event.capacity - event.capacity.length
      }
    })
    return { event }
  }
}

正如上面代码底部所示,我创建了一个新的事件常量,它接受一个普通的 JavaScript 对象并返回一个响应式对象。在我们的常规组件语法中使用 data 选项可能看起来很熟悉,我也在其中发送了一个对象。但是,正如您在上面看到的,我也可以将我们的计算属性发送到这个对象中。您还应该注意到,当我使用这种语法时,我们在访问属性时不再需要编写 .value。这是因为我只是在访问事件对象上的对象属性。您还应该注意到我们将返回整个活动

两种语法都可以使用,都不是最佳实践

于 2020-04-27T15:08:17.900 回答