Halo
发布于 2023-10-16 / 98 阅读 / 0 评论 / 0 点赞

vue中ref和reactive的区别

区别和联系

  • reactive() only takes objects, NOT JS primitives (String, Boolean, Number, BigInt, Symbol, null, undefined)
  • ref() is calling reactive() behind the scenes
  • Since reactive() works for objects and ref() calls reactive(), objects work for both
  • BUT, ref() has a .value property for reassigning, reactive() does not have this and therefore CANNOT be reassigned
  • ref() seems like the way to go since it supports all object types and allows reassigning with .value. ref() is a good place to start, but as you get used to the API, know that reactive() has less overhead, and you may find it better meets your needs.

使用场景

ref() when..

  • it's a primitive (for example 'string', true, 23, etc)
  • it's an object you need to later reassign (like an array - more info here)
setup() {
    const blogPosts = ref([]);
    return { blogPosts };
}
getBlogPosts() {
    this.blogPosts.value = await fetchBlogPosts();
}

reactive() when..

  • it's an object you don't need to reassign, and you want to avoid the overhead of ref()
setup() {
    const blog = reactive({ posts: [] });
    return { blog };
}
getBlogPosts() {
    this.blog.posts = await fetchBlogPosts();
}

评论