Vue 3 có gì mới? – What’s new from Vue 3?

Bài viết được sự cho phép của tác giả Kiên Nguyễn

Bản thân tôi rất yêu thích Vuejs, không ngạc nhiên khi luôn trông chờ, tìm hiểu xem Vue 3 có gì mới?. Quả nhiên Vue 3 không làm tôi thất vọng.

Với những cải tiến đáng giá từ performance cho tới API,điển hình là sự ra đời của Composition API thay cho Options API ở Vue 2.

  3 phút làm quen với Vue.js
  API Authentication trong Laravel-Vue SPA sử dụng Jwt-auth

Bắt đầu ngay thôi nào!

1. Vue 3 có gì mới?

Không những thay đổi lớn về performance, không thể chê được vào đâu khi bổ sung hàng loạt tính năng mới, nhưng kích thước của Vue 3 cũng chỉ bằng Vue 2 (12KB).

Cải tiến đáng giá được nhắc tới trong bài viết này bao gồm:

  • Composition API
  • Multiple root elements
  • Suspense
  • Multiple v-models

Sơ bộ anh em có thể xem qua video này để nắm bắt thêm Vue 3 có gì mới nha!.

2. Composition API

Kể từ khi Vue 2 nổi lên như là ngôi sáng sáng giữa bầu trời, rất nhiều dự án lớn đã sử dụng Vue. Một khi dự án lớn (cỡ vài trăm component), vấn đề tái sử dụng (reusable code) và scability (mở rộng) trở nên quan trọng hơn bao giờ hết.

Ok, Composition API là câu trả lời đầu tiên cho Vue 3 có gì mới?. Vậy Composition API là gì?

Composition API as a reactive API coupled with the ability to register lifecycle hooks using globally imported functions.

Composition API là thành phần của Reactive API, với khả năng đăng kí các lifecycle hooks sử dụng các import global cho functions.

Quất thêm cái nữa khó hiểu hơn:

The main point is that the Composition API provides a different way to manage reactivity at all points in an application, without compromising organization and readability.

Điểm mấu chốt mà Composition API cung cấp là một “cách khác” để quản lý reactivity tất cả các điểm trong application, mà không ảnh hưởng tới tổ chức code và khả năng đọc hiểu.

Vãi nồi khó hiểu, đọc vậy mông lung như một trò đùa.

2.1 Dễ hiểu hơn được không?

Thực chất Composition API cho phép ta đóng gói một loạt các method trong life cycle. Ví dụ, trước kia ở Vue 2, created tính toán, chuẩn bị dữ liệu cho object A, watch theo dõi object A khi thay đổi, … Vô vàn thứ cần làm với A. Source code trở nên mất kiểm soát, khó hiểu nếu bạn không phải là người viết ra component đó.

Vue 3 có gì mới? – What’s new from Vue 3?
Các vùng có màu khác nhau thì độc lập với nhau. Nội đủ hết method trong life cycle cũng đã là nhiều với component.

Chính bởi khi có quá nhiều Component và nhiều logic phức tạp. Khó maintain và scale, nên ta cần tới Composition API.

Vue 3 có gì mới? – What’s new from Vue 3?
Với Composition API, tất cả các đoạn code xử lý liên quan tới Object A có thể được gom lại duy nhất ở setup.

Tuy nhiên, đừng quên là Vue 3 vẫn hỗ trợ Options API, nên nếu muốn, không có vấn đề gì khi cứ viết các method theo Life Cycle của Vue nha. Với Options API, cùng lướt qua component vô cùng đơn giản với Options API.

Vue.js Component

<template>
<div id="app">
<p>You clicked {{ numOfClicks }} times.</p>
<button @click="handleClick()">Click me to increment!</button>
</div>
</template>

<script>
export default {
name: "App",
data() {
return {
numOfClicks: 0,
};
},
created() {},
methods: {
handleClick: function () {
this.numOfClicks++;
},
},
};
</script>

<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

Ví dụ sử dụng Composition API với setup()

Vue.js Component

<template>
<div id="app">
<p>You clicked {{ numOfClicks }} times.</p>
<button @click="handleClick()">Click me to increment!</button>
</div>
</template>

<script>
import { ref } from "vue";

export default {
name: "App",
setup() {
let numOfClicks = ref(0);

function handleClick() {
numOfClicks.value++;
}

return {
handleClick,
numOfClicks,
};
},
};
</script>

<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

Tuy nhiên, sử dụng Composition API cần lưu ý:

Because the component instance is not yet created when setup is executed, there is no this inside a setup option. This means, with the exception of props, you won’t be able to access any properties declared in the component – local statecomputed properties or methods.

Bởi vì Component instance chưa hề được tạo ra khi method setup được thực thi, nên this chắc chắn không work. Ngoại trừ cái thằng props ra, tuyệt nhiên ta không thể access tới bất cứ properties nào khai báo trong component, local state, computed properties hoặc methods cũng không là ngoại lệ.

3. Multiple root elements

Multi root elements ở đây được hiểu là component không cần phải thuộc về duy nhất một node cha nữa. Câu trả lời thứ 2 cho Vue 3 có cái gì mới xem ra dễ hiểu hơn nhiều!.

Bai bai cái lỗi khó chịu quỷ tha ma bắt này. Bắt đầu từ Vue 3, một component có thể có nhiều hơn một node cha.

Vue 3 có gì mới? – What’s new from Vue 3?

Vue.js Component

<template>
<div class="counter">
<p> Count: {{ count }} </p>
<button @click="increment"> Increment </button>
<button @click="decrement"> Decrement</button>
</div>
</template>

Tha hồ, mặc sức mà tạo node con trong template với Vue 3. Việc bỏ đi một node cha cũng bớt phiền phức khi làm việc với css. Trước đây 2 tag p nếu bắt buộc chung nhau 1 div phải viết css parent child mệt mỏi. Tuy nhiên, giờ mạnh ai người đó xài css của mình.

Vue.js Component

<template>
<p> Count: {{ count }} </p>
<button @click="increment"> Increment </button>
<button @click="decrement"> Decrement</button>
</template>

4. Suspense

Suspense là cái tiến mới ở Vue 3 liên quan tới Asynchorous (Bất đồng bộ). Trước đây khi làm việc với API, do việc xử lý call API là bất đồng bộ, nên cần chờ tới khi có response trả về mới thực hiện render.

Thông thường sử dụng v-if, tuy nhiên với Suspense, mọi việc trở nên đơn giản hơn nhiều.

Suspense is a special component that renders a fallback content instead of your component until a condition is met.

Suspense là component dặc biệt render nội dung dự phòng thay vì component chính (lúc này chưa có data), cho tới khi condition (điều kiện để render component) được xác lập.

Sử dụng Suspense cũng khá đơn giản, chỉ cần lưu ý tới 2 từ khóa default và fallback. Cùng xem xét ví dụ sau:

Vue.js Component

<template>
<Suspense>
// Sau khi đã có response từ API, nội dung template này sẽ render sau.
<template #default>
<div v-for="item in articleList" :key="item.id">
<article>
<h2>{{ item.title }}</h2>
<p>{{ item.body }}</p>
</article>
</div>
</template>
// Trước khi có data từ API, nội dung trong template này sẽ tải trước
<template #fallback>
Articles loading...
</template>
</Suspense>
</template>
<script>
import axios from 'axios'
export default {
async setup() {
let articleList = await axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log(response)
return response.data
})
return {
articleList
}
}
}
</script>

5. Multiple V-models

Làm việc với Vue 2 chắc chắn đã biết tới v-models. V-models là two way binding. Dữ liệu binding 2 chiều, thường được sử dụng với form trên component.

Hữu dụng là thế, tuy nhiên Vue 2 chỉ cho phép một component có duy nhất một v-models. Vue 3 thì khác, cho phép không giới hạn số lượng v-model trong component.

Vue.js Component

<template>
<Suspense>
// Sau khi đã có response từ API, nội dung template này sẽ render sau.
<template #default>
<div v-for="item in articleList" :key="item.id">
<article>
<h2>{{ item.title }}</h2>
<p>{{ item.body }}</p>
</article>
</div>
</template>
// Trước khi có data từ API, nội dung trong template này sẽ tải trước
<template #fallback>
Articles loading...
</template>
</Suspense>
</template>
<script>
import axios from 'axios'
export default {
async setup() {
let articleList = await axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log(response)
return response.data
})
return {
articleList
}
}
}
</script>

6. Tham khảo

Thank for read the article – Have a nice weekend – Happy coding!

Bài viết gốc được đăng tải tại kieblog.vn

Có thể bạn quan tâm:

Xem thêm Việc làm Developer hấp dẫn trên TopDev