Our Global Presence
Canada
57 Sherway St,
Stoney Creek, ON
L8J 0J3
India
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
USA
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
With Vue 3 gaining traction and becoming the new default, many things are changing, and the ecosystem is still shaping. Until recently, the choice for state management was clearly Vuex. But with the new composition API architecture, reactivity mechanism, and some new players in the game, the choice now might be different.
Let’s explore different ways of managing the state depending on your application size and try to predict what the future of State Management in Vue.js will look like.
In options API, you can declare reactive data for a component using the data() option. Internally the object returned is wrapped with the reactive helper. This helper is also available as a public API.
If you have a piece of state that should be shared by multiple instances, you can use reactive() to create a reactive object and then import it from multiple components:
With this approach, data are centralized and can be reused across components. This can be a simple option with a minimal footprint for a small application.
A similar concept that composition API brought to the table is using a composable. This pattern, which is very popular in the React world, combined with the powerful reactivity mechanism of Vue can produce some elegant and reusable composables like the following.
Vuex is not going away. It supports Vue 3 with the same API and minimal breaking changes. The only change is that installation must happen on a Vue instance instead of the Vue prototype directly.
Vuex 4 will still be maintained. However, it’s unlikely that new functionalities will be added to it. It’s a good option if you already have a project using Vuex 3 and want to defer the migration to something else for later.
Pinia is a new store/state management system for Vue. This is a great tool for when wanting to share data between components in your application. One of the reasons for using a tool like Pinia (or Vuex for that matter) is that throwing events around and listening for these events in your application can easily become quite messy and unstructured. State management systems like Pinia (Vuex, Redux, etc.) can help solve this.
Pinia is now also the recommended choice by Vue and is now an official part of the whole Vue ecosystem, maintained and developed by core members of the Vue team. Last but not least, Pinia is super lightweight, only 1kb in size which is freaking awesome.
Pinia supports an alternative syntax to define stores. It uses a function that defines reactive properties and methods and returns them very similar to the Vue Composition API’s setup function.
In Setup Stores:
Setup stores bring a lot more flexibility than Options Stores as you can create watchers within a store and freely use any composable.
The state is a function that holds all the reactive data of this store and the getters are functions with access to the store as the first parameter. Both state and getters are identical to Vuex.
This statement doesn’t apply to actions. The context parameter has gone, and actions have access to the state and getters directly through their context(this). As you might have noticed, actions directly manipulate the state, which was strictly forbidden in Vuex.
Lastly, mutations are completely removed since state manipulation is now happening in actions.
All the magic is happening inside the setup function. The imported useFellowship hook is executed and returned. This will make it available to the component, including both methods and the template. Access to the state getters and actions are done directly using this object.
Of course, this component should be broken into smaller reusable ones but left like this for demo purposes.
If a different component needs to access the same state, it can be done in a similar manner.
Pinia docs are optimistic that code can be reused between the libraries, but the truth is that the architecture is very different, and refactoring will definitely be required. First of all, while in Vuex, we had one store with multiple modules, Pinia is built around the concept of multiple stores. The easiest way to transition that concept to be used with Pinia is that each module you used previously is now a store.
Actions no longer accept context as their first parameters. They should be updated to access state or any other context property directly. The same applies for rootState, rootGetters etc. since the concept of a single global store doesn’t exist. If you want to use another store you need to explicitly import it.
It’s evident that for large projects, migration will be complicated and time-consuming, but hopefully, a lot of boilerplate code will be eliminated, and the store will follow a more clean and modular architecture. The conversion can be done module by module rather than converting everything at once. You can actually mix Pinia and Vuex together during the migration so that this approach can work.
For more information and to develop a website using Vue.js, Hire Vue.js Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop a Website using Vue.js, please visit our technology page.
Content Source:
Vue 3 – The Progressive Javascript Framework’s progress over the years is nothing short of impressive.
If you’re someone migrating your apps to Vue 3 (or) experimenting Vue 3 for your next project this draft should help you kickstart with confidence.
If we look at the journey of Vue so far, it greatly traversed being a library to a framework trend making it much more powerful yet sticking to its lightweight nature.
With the core releasing a new major version, all the other parts of the framework needed to move forward together. Having said that, there were quite a lot of new members we would have in our party during migration. Let’s get introduced!
In short, Vue 3 would be the new default.
Vue 2 would remain in LTS (long-term support) version for 18 months, which means that it will still get security updates and is absolutely safe to stick with it for a while. But, isn’t it a great time for us to migrate our existing projects if any?
Vue 3 is faster, smaller, more maintainable and it’s easier to target native - Evan Vue
Smaller Vue core – Size improvement reached by the combination of greater code modularity, a smaller core runtime, and a tree-shaking-friendly compiler. Thus the new core would thus be reduced from about 20KB to 10KB gzipped.
The compiler will generate tree-shaking-friendly code. If you use a feature that requires a function in your template, the compiler will automatically generate code that imports it. But if you don’t use a feature, then we generate code that does not import it, which means the feature will be tree-shaken.
Better rendering performance – The Vue 3 renderer improves the performance of the rendering process by using optimizations such as the hoisting and inlining of static parts and implementing Vue 3’s reactivity with ES6 proxies.
Below is an infographic proofing the metrics between v-2.5 and v.3.0 proto
Well, despite being one of our favorite topics to speak We’ll try to wrap it short.
Vite is a lightweight and fast build toolchain with first-class Vue SFC support. It is created by Evan You, the author of Vue himself!
Vue 3 official build setup is now powered by Vite. So this would be one of our newest members to welcome!
This topic deserves a separate article on its own, yet will try to pin those dancing in my mind post my experimentations.
Vue 3 introduced the Composition API as an alternative method to the Options API for writing component states and logic. It’s simply a set of APIs that allows us to author Vue components using imported functions instead of declaring options.
It is an umbrella term that covers the following APIs:
Reactivity API, e.g. ref() and reactive(), allows us to directly create reactive state, computed state, and watchers.
Lifecycle Hooks, e.g. onMounted() and onUnmounted(), allows us to programmatically hook into the component lifecycle.
Dependency Injection, i.e. provide() and inject(), allows us to leverage Vue’s dependency injection system while using Reactivity APIs.
Vue clearly pointed out that they don’t have any plans to deprecate options API. Here’s the exact statement from the document FAQ
No, we do not have any plan to do so. Options API is an integral part of Vue and the reason many developers love it. We also realize that many of the benefits of Composition API only manifest in larger-scale projects, and Options API remains a solid choice for many low-to-medium-complexity scenarios.
We can create standalone reactive states and/or properties
In Vue 2 we’re kind of bound to the component scope for the reactive state. With Vue 3 you don’t need a component anymore to create a reactive state.
We can abstract reactive state
Sometimes setup in Vue components can get really bloated with creating many reactive properties. That’s why it could be nice to have them abstracted in standalone javascript files. This is preferably termed composable.
Better Logic Reuse
The primary advantage of Composition API is that it enables clean, efficient logic reuse in the form of Composable functions. It solves all the drawbacks of mixins, the primary logic reuse mechanism for Options API
Better Type Inference
Code written in Composition API can enjoy full type inference with little need for manual type hints.
Smaller Production Bundle and Less Overhead
Code written in Composition API and <script setup> is more efficient and minification-friendly than Options API equivalent. This is because the template in a <script setup> component is compiled as a function inlined in the same scope of the <script setup> code. Unlike property access from this, the compiled template code can directly access variables declared inside <script setup>, without an instance proxy in between. This also leads to better minification because all the variable names can be safely shortened.
Better code sharing
Inside the setup hook, we can group parts of our code by logical concern.
More Flexible Code Organization
The Options API uses options like data, methods, and mounted. With the Composition API, we have a single setup hook in which we write our reactive code.
This results in better code organization. Let’s see how with a simple code example. We’ll see how we write in Vue2, rewrite in composition API then further fine-tune with the new script setup syntax.
Having said Vue doesn’t have plans to deprecate options API anytime soon. Why should we care about composition API?
Vue 2 supports a few ways to reuse code between components;
These methods of reuse each come with their own drawbacks, namely:
Scattered logics – In Vue2, component options such as data, computed, methods, watch are used to organize the logic. This approach makes it hard to read and understand as the component grows.
<script setup> is a compile-time syntactic sugar for using Composition API inside Single File Components (SFCs). It is the recommended syntax if we are using both SFCs and Composition API. It provides a number of advantages over the normal <script> syntax:
More succinct code with less boilerplate
Ability to declare props and emitted events using pure TypeScript
Better runtime performance (the template is compiled into a render function in the same scope, without an intermediate proxy)
Better IDE type-inference performance (less work for the language server to extract types from code)
Unlike normal <script>, which only executes once when the component is first imported, code inside <script setup> will execute every time an instance of the component is created. <script setup> can be used alongside normal <script>
Pinia, a lightweight state management library for Vue.js, allows us to share a state across components/pages & gained a lot of traction recently. It uses the new reactivity system in Vue 3 to build an intuitive and fully typed state management library. It’s now the new default state management library for Vue 3. It is maintained by the Vue core team and works with both Vue 2 and Vue 3.
For more information and to develop a website using Vue.js, Hire Vue.js Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”.
To develop a Website using Vue.js, please visit our technology page.
Content Source:
Vue 3 isn’t officially released yet, but the Vue team has released the Alpha version to use some of the features that will be shipped with Vue 3.
We’ll use the WebPack-based setup.
To do this, clone this repository:
git clone https://github.com/vuejs/vue-next-webpack-preview.git vue-next cd vue-next
Now install the packages:
npm install
That’s it. We have a working Vue 3 project set up now.
To spin up the application, just run the following:
npm run dev
Open localhost:8080
in your browser, and you can see a simple counter application.
Open the package.json
file, you can see the Vue version here. At the time of writing this article, the version is 3.0.0-alpha.8
.
Open App.vue
and you’ll see the setup()
method, i.e. the Composition API already being used here. We might see some lint errors from Vue’s official plugin, eslint-plugin-vue
, because the linters are not yet updated to understand the new syntax.
Before we start coding, let’s go over the new features in Vue 3.
Vue 3 is faster, smaller in file size, and equipped with better TypeScript support. Some of the new features that we can discuss and learn to implement in this article include:
Composition API was launched as a plugin a few months back, so there is nothing new there, but in Vue 3 we don’t have to install it like a plugin anymore. Now, it’s built into the package and can be used out of the box without any additional setup.
There are two main advantages to using the Composition API:
If you are new to Composition API, here is how we can use it to implement a component:
<template> <div class="counter"> <p>count: {{ count }}</p> <p>NewVal (count + 2): {{ countDouble }}</p> <button @click="inc">Increment</button> <button @click="dec">Decrement</button> <p> Message: {{ msg }} </p> <button @click="changeMessage()">Change Message</button> </div> </template> <script> import { ref, computed, watch } from 'vue' export default { setup() { /* ---------------------------------------------------- */ let count = ref(0) const countDouble = computed(() => count.value * 2) watch(count, newVal => { console.log('count changed', newVal) }) const inc = () => { count.value += 1 } const dec = () => { if (count.value !== 0) { count.value -= 1 } } /* ---------------------------------------------------- */ let msg= ref('some text') watch(msg, newVal => { console.log('msg changed', newVal) }) const changeMessage = () => { msg.value = "new Message" } /* ---------------------------------------------------- */ return { count, inc, dec, countDouble, msg, changeMessage } } } </script>
And here’s the equivalent code in Options API:
<template> <div class="counter"> <p>count: {{ count }}</p> <p>NewVal (count + 2): {{ countDouble }}</p> <button @click="inc">Increment</button> <button @click="dec">Decrement</button> <p> Message: {{ msg }} </p> <button @click="changeMessage()">Change Message</button> </div> </template> <script> export default { data() { return { count: 0, msg: 'some message' } }, computed: { countDouble() { return this.count*2 } }, watch: { count(newVal) { console.log('count changed', newVal) }, msg(newVal) { console.log('msg changed', newVal) } }, methods: { inc() { this.count += 1 }, dec() { if (this.count !== 0) { this.count -= 1 } }, changeMessage() { msg = "new Message" } } } </script>
We can see that using Composition API allows us better organization by keeping the the code (state, methods, computed properties, watchers etc) of particular features together, which was not possible in Options API.
In the above example, the code for counter
and the code for changing a message
is clearly separated in Composition API.
Using the Composition API makes sharing the code much easier. We can factor out the code for a particular feature and use it in multiple places, as shown below:
//message.js import { ref, watch } from 'vue' export function message() { let msg = ref(123) watch(msg, newVal => { console.log('msg changed', newVal) }) const changeMessage = () => { msg.value = 'new Message' } return { msg, changeMessage } }
Using the shared code in our component
<template> <div class="counter"> <p>count: {{ count }}</p> <p>NewVal (count + 2): {{ countDouble }}</p> <button @click="inc">Increment</button> <button @click="dec">Decrement</button> <p>Message: {{ msg }}</p> <button @click="changeMessage()">change message</button> </div> </template> <script> import { ref, computed, watch } from 'vue' import { message } from './common/message' export default { setup() { let count = ref(0) const countDouble = computed(() => count.value * 2) watch(count, newVal => { console.log('count changed', newVal) }) const inc = () => { count.value += 1 } const dec = () => { if (count.value !== 0) { count.value -= 1 } } let { msg, changeMessage } = message() return { count, msg, changeMessage, inc, dec, countDouble } } } </script>
In Vue 2, the template tag can only take one root element. Even if we had just two <p>
tags, we had to enclose them within a <div>
tag to get it working. Because of this, we had to change the CSS code as well in the parent component so that it looked as expected.
In Vue 3, this restriction is lifted. There is no need for a root element anymore.
We can use any number of tags directly inside the <template></template>
section:
<template> <p> Count: {{ count }} </p> <button @click="increment"> Increment </button> <button @click="decrement"> Decrement</button> </template>
Equivalent code in Vue 2:
<template> <div class="counter"> <p> Count: {{ count }} </p> <button @click="increment"> Increment </button> <button @click="decrement"> Decrement</button> </div> </template>
Suspense is a new feature that renders a default/fallback component until the main component fetches the data.
Sometimes we use async operations to fetch data from the server. Instead of handing the template with v-if and then setting it back when we return the data, Suspense does it for us.
Suspense can be used for both parts of the template, or the whole template:
<template> <Suspense> <template #default> <div v-for="item in articleList" :key="item.id"> <article> <h2>{{ item.title }}</h2> <p>{{ item.body }}</p> </article> </div> </template> <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>
We all know that v-model is used for two-way binding. We mostly use it with form elements. Sometimes, we even use it with custom components.
Vue-2 allowed the use of only one v-model on a component. In Vue-3, we can bind any number of v-models to our custom components:
<template> <survey-form v-model:name="name" v-model:age="age"> </survey-form> </template> //SurveyForm.vue <template> <div> <label>Name: </label> <input :value="name" @input="updateName($event.target.value)" /> <label>Age: </label> <input :value="age" @input="updateAge($event.target.value)" /> </div> </template> <script> export default { props: { name: String, age: Number }, setup(props, { emit }) { const updateName = value => { emit('update:name', value) } const updateAge = value => { emit('update:age', +value) } return { updateName, updateAge } } } </script>
Vue 2 already had great reactivity, and you might not have come across any cases where you found that reactivity was lacking. However, there were a few cases where Vue 2 fell short.
Let’s revisit Vue 2 and see what those limitations were.
To demonstrate reactivity, we’ll use watchers to listen to one of the state variables and then modify it to see if the watchers are triggered:
<template> <div class="hello" @click="test">test {{list }} {{ myObj }}</div> </template> <script> export default { name: "HelloWorld", data() { return { list: [1, 2], myObj: { name: "Preetish" } }; }, watch: { list: { handler: () => { console.log("watcher triggered"); }, deep: true } }, methods: { test() { this.list[2] = 4; this.myObj.last = "HS"; delete this.myObj.name; } } }; </script>
None of the above three modifications — such as adding a new item to an array based on the index, adding a new item to an object, or deleting an item from the object — is reactive in Vue-2. Hence watchers
won’t be triggered, or the DOM would be updated. We had to use the vue.set()
or vue.delete()
methods.
In Vue-3, these work directly without any helper functions:
export default { setup() { let list = ref([1, 2]) let a = ref(0) let myObj = ref({ name: 'Preetish' }) function myFun() { list.value[3] = 3 myObj.value.last = 'HS' delete myObj.value.name } return { myFun, list, myObj } } }
We can see that watcher
was triggered all four times in the Vue 3 setup.
When you open main.js
in the about
project, you’ll notice something different. We no longer use the Global Vue instance to install plugins and other libraries.
Instead, you can see createApp
method:
import { createApp } from 'vue' import App from './App.vue' const myApp = createApp(App) myApp.use(/* plugin name */) myApp.use(/* plugin name */) myApp.use(/* plugin name */) myApp.mount('#app')
The advantage of this feature is that it protects the Vue application from third party libraries/plugins we use which might override or make changes to the global instance — mostly by using Mixins.
Now with the createApp
method, we install those plugins on a particular instance and not the global object.
Portal is a feature where we can render a part of the code which is present in one component into a different component in a different DOM tree. There was a third-party plugin called portal-vue
that achieved this in Vue 2.
In Vue 3, portal will be built in and it is very easy to use.
Vue 3 will have a special tag called <Teleport>
, and any code enclosed within this tag will be ready to be teleported anywhere. The Teleport
tag takes a to
argument.
Let’s see this in action:
<Teleport to="#modal-layer"> <div class="modal"> hello </div> </Teleport>
Any code inside <Portal></Portal>
will be displayed in the target location mentioned.
<div id="modal-target"></div>
At the time of writing this article, <Teleport>
doesn’t work in the Alpha version mentioned above.
For more information and to develop website using Vue.js, Hire Vue.js Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft”. To develop Website using Vue.js, please visit our technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2024 — HK Infosoft. All Rights Reserved.
© 2024 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap