Full text
University of Minho School of Engineering Pedro Alexandre Travassos da Silva Melo From Vue2.0 to Vue3.0: application migration october 2024
University of Minho School of Engineering Pedro Alexandre Travassos da Silva Melo From Vue2.0 to Vue3.0: application migration Master’s Dissertation in Informatics Engineering Dissertation supervised by José Carlos Leite Ramalho october 2024
Copyright and Terms of Use for Third Party Work This dissertation reports on academic work that can be used by third parties as long as the internationally accepted standards and good practices are respected concerning copyright and related rights. This work can thereafter be used under the terms established in the license below. Readers needing authorization conditions not provided for in the indicated licensing should contact the author through the RepositóriUM of the University of Minho. License granted to users of this work: CC BY-NC-ND https://creativecommons.org/licenses/by-nc-nd/4.0/ i
Statement of Integrity I hereby declare having conducted this academic work with integrity. I confirm that I have not used plagiarism or any form of undue use of information or falsification of results along the process leading to its elaboration. I further declare that I have fully acknowledged the Code of Ethical Conduct of the University of Minho. University of Minho, Braga, october 2024 Pedro Alexandre Travassos da Silva Melo ii
Abstract In the context of the Masters in Informatics Engineering, it has been written a dissertation and developed a prototype that is a product of the migration of the CLAV platform from Vue 2 to Vue 3. Vue is a front-end framework used by major international technology companies such as Apple, Microsoft and Google and tries to compete with other similar frameworks such as Meta’s React, Microsoft’s Blazor and Google’s Angular. Version 2 has recently been discontinued, meaning that it no longer receives general updates including security and browser compatibility. If someone wants to continue using Vue 2, the company HeroDevs, in partnership with Vue, offers endless support for Vue 2 which promises security, compatibility with the most popular browsers and support for essential libraries, all through regular updates. The new version of Vue introduces significant changes that make it incompatible with the previous version, so it will take a significant effort to migrate projects to the new version. However, most of Vue’s APIs have been maintained, so there’s no need to relearn how the framework works. The team that develops Vue intends to avoid upgrades that involve migrating between versions in the future and its priority is the compatibility and stability of the framework. In short, this dissertation presents a technical report summarizing the changes between Vue versions 2 and 3, which includes a map of transformations to apply in order to migrate applications from one version to the other, as well as a functional prototype implemented in Vue 3 of the selected subset of CLAV. Furthermore, there were left recommendations to follow to continue the migration of CLAV which will be done in the future by other persons. Keywords Vue, Migration, CLAV, Ontology iii
Resumo No contexto do Mestrado em Engenharia Informática, foi escrita uma dissertação e desenvolvido um protótipo que é um produto da migração da plataforma CLAV de Vue 2 para Vue 3. O Vue é uma framework front-end usada pelas maiores empresas de tecnologia internacionais tais como a Apple, Microsoft e Google e tenta competir com outras frameworks semelhantes tais como o React da Meta, o Blazor da Microsoft e o Angular da Google. Recentemente a versão 2 foi descontinuada, ou seja, deixou de receber atualizações no geral incluindo de segurança e de compatibilidade com browsers. Se alguém quiser continuar a usar o Vue 2, a empresa HeroDevs, em parceria com o Vue, oferece suporte interminável para Vue 2 que promete segurança, compatibilidade com os browsers mais populares e suporte para bibliotecas essenciais, tudo através de atualizações regulares. A nova versão do Vue apresenta mudanças significativas que a tornam incompatível com a versão anterior daí que será necessário um esforço significativo para migrar projetos para a nova versão. No entanto, a maioria das APIs do Vue mantêm-se e por isso não é necessário aprender de novo todo o funcionamento da framework. A equipa que desenvolve o Vue tem intenções de no futuro evitar atualizações que impliquem efetuar uma migração entre versões e tem como prioridade a compatibilidade e estabilidade da framework. Em suma, esta dissertação apresenta um relatório técnico resumindo as alterações entre as versões 2 e 3 do Vue, onde está incluído um mapa de transformações a aplicar para fazer a migração de aplicações de uma versão para a outra, bem como um protótipo funcional implementado em Vue 3 do subconjunto selecionado do CLAV. Além disso, foram deixadas recomendações a seguir para continuar a migração do CLAV que será efetuada no futuro por outras pessoas. Palavras-chave Vue, Migração, CLAV, Ontologia iv
Contents 1 Introduction 1 1.1 Context ........................................ 1 1.2 Work Methodology .................................. 1 1.3 Document Structure .................................. 2 2 State of the Art 3 2.1 What is Vue? ..................................... 3 2.2 Why use Vue? ..................................... 4 2.3 Vue 3 Lifecycle .................................... 4 2.4 Vue 3 Application Structure .............................. 6 3 Case Study 8 3.1 What is CLAV? .................................... 8 3.2 Definition of CLAV Ontology .............................. 9 3.2.1 Consolidated List ............................... 9 3.2.2 Selection Tables ............................... 10 3.3 Science of Ontology .................................. 12 4 Main decisions when migrating CLAV 15 4.1 Recreating CLAV ................................... 15 4.2 Vuetify ........................................ 15 5 Transformation Map 18 5.1 Changes to the initialization of a Vue application .................... 18 5.1.1 A New Global API ............................... 18 5.2 Changes to the code ................................. 22 5.2.1 Options API vs Composition API coupled with SFCs .............. 22 v
5.2.2 Components ................................. 25 5.2.3 Directives .................................. 26 5.2.4 Props .................................... 32 5.2.5 Emits .................................... 34 5.2.6 Computed Properties ............................. 35 5.2.7 Watchers Vue 2 vs Vue 3 ........................... 37 5.2.8 Nested Objects ................................ 38 5.2.9 SFC State-driven CSS Variables ........................ 39 5.2.10 Vuetify .................................... 40 5.3 Changes in Vue’s router ................................ 41 5.3.1 Router creation, access and routes definition. ................. 41 5.3.2 Other significant changes in the router .................... 42 5.4 Libraries ....................................... 45 5.5 Directories Structure ................................. 46 6 Case Study Development with Vue 3 47 6.1 Summary ....................................... 47 6.2 Homepage Interface ................................. 48 6.3 Authentication Interface ................................ 49 6.4 List of Classes Interface ................................ 51 6.5 Selection Tables Interface ............................... 56 6.6 List of Entities Interface ................................ 59 6.7 List of Typologies of Entities Interface ......................... 60 6.8 Legislations Interface ................................. 61 7 Conclusions and future work 63 vi
Chapter 2 State of the Art This chapter will explain what is Vue and present the capabilities of Vue. 2.1 What is Vue? Vue is a front-end framework that allows for the creation of reactive user interfaces. This kind of user interfaces are event driven and the user is quickly aware of the response to its own interactions, such as keyboard, mouse, voice or other forms of input, and the user is always up to date with the state of the application. Being an event driven UI framework means that when the state of the UI changes due to an user’s action, a response is triggered which causes some events and state transitions. It’s basically the app responding to a change in its environment. Vue is used to build Single-Page Applications (SPA) which are apps or websites that only have one page. So instead of an application built with the traditional Model-View-Controller (MVC) software design pattern in which the user has to wait for a page to be fully rendered when making a request, in SPAs the user is always on the same page because when making a request the response includes only the necessary data to update the content of the page thus making the app quicker and its transitions look smoother. Also another key difference between MVC apps and SPAs is that while MVC’s layers are more independent (models, views and controllers), SPAs offer a component architecture in which the code and UI are closely tied together logically and physically. 3
2.2 Why use Vue? Vue has been used by developers worldwide since 2014 because it provides all the features required to create and scale high-performance applications. Vue is a solid framework that offers the appropriate tools for projects of any size, regardless of whether it’s a new startup, a well-established business or an independent freelancer. Declarative rendering and an advanced reactivity system are built into Vue’s core, which lets it do most of the hard work for you. Being Vue a progressive framework, you can begin with its core library and add more features as you need them. Routing, state management, testing tools, a command-line interface, and other integrated solutions are all part of its ecosystem. Because Vue is designed to integrate easily with other well-known technologies, such as TypeScript, developers can customize it to fit their unique workflow. Because of its careful design, applications stay quick even as they expand by avoiding needless re-renders. Vue maintains high performance by automatically optimizing code during compilation, eliminating the need for manual optimization. This framework gives developers a better productivity thus allowing to have more time for the creative process. Developers who choose Vue are choosing a technology that will stay up to date to with modern practices, but that also fulfils their requirements. 2.3 Vue 3 Lifecycle Vue components have a lifecycle that begin at their creation and terminate when they are no longer rendered on the screen. Lifecycle hooks are events that can be activated in certain parts of the execution of code. This hooks are like triggers that can alter the state of the application in various stages of the program. The lifecycle is organized in 4 phases: • Creation • Mounting • Updating • Unmounting 4
The creation phase occurs before the component is completely initialized, so it’s still not visible. The mounting phase takes place when the component is mounted into the DOM and rendered in the browser. The updating phase happens when reactive data changes, which forces the component to be re-rendered. Finally, when the lifecycle reaches the unmounting phase, the component is unmounted from the DOM and stops being rendered in the browser. Figure 1: Vue 3 Lifecycle diagram - Source VUE (2023b) 5
2.4 Vue 3 Application Structure The following image shows the CLAV’s front-end application structure, which is the recommended structure to follow when building any app in Vue 3. Figure 2: CLAV Front-end - Vue 3 application structure. Succinctly, this is what is contained in each folder: • node_modules/ - NPM dependencies • public/ - Static assets (e.g. webpage icon) • src/ - Source code –assets/ - Images, fonts, styles (SCSS variables) –components/ - Vue components –config/ - Useful custom variables –pages/ - The views which the user navigates –plugins/ - Imports of plugins –router/ - Router configuration –store/ - Pinia state management 6
–utils/ - Useful custom constant variables –App.vue - Root component for the application –main.ts - Bootstraps Vuetify and other plugins (store, router) then mounts the app –vite-env.d.ts - Modules declaration (e.g. *.vue files) • index.html - HTML file from where the app is started • package.json - Project configuration (dependencies, scripts, etc.) • vite.config.js - Vite configuration This chapter quickly described what Vue is and why one should use it. The Vue framework offers immense potential and is suited for front-end development. Understanding the state-of-the-art is crucial to be up-to-date with the newest mechanisms of Vue and its core engineering: the component lifecycle. This offers the possibility of modifying the state of a component in its different stages, from its initial creation to its final dissolution. In the next chapter, we will take a look at the platform that serves as a case study and makes good use of Vue: CLAV. 7
Chapter 3 Case Study CLAV is the case study of the dissertation and this chapter will explain what it is and its importance. 3.1 What is CLAV? As described in the official website: ”Platform of the Directorate-General for Books, Archives and Libraries to provide information, guidelines and tools to facilitate and standardize the practices of classifying and evaluating public information. This platform is aimed at public administration bodies, public companies and other entities in mainland Portugal allowing them to interact with the DGLAB and create a common reference for the classification of information. It is also aimed at citizens, particularly through the availability of the Public Administration business process catalog, which is part of the Consolidated List.” In Portuguese, CLAV stands for CL assificação e AV aliação da Informação Pública which translates to Classification and Evaluation of the Public Information. The following image shows the CLAV website in Vue 2: Figure 3: CLAV website in Vue 2 8
3.2 Definition of CLAV Ontology CLAV is structured as an ontology so it’s important to get a notion of what are CLAV’s main components and what ontology means. 3.2.1 Consolidated List The Consolidated List aims to classify and evaluate public documentation. It’s a list of classes/processes of the Public Administration (AP) organized in a hierarchy of blocks separated by a dot. Each classes has a level associated that informs the user about its purpose. Level 1 classes are related to AP’s functions, level 2 to AP’s sub-functions, level 3 to AP’s business processes and level 4 to AP’s subdivision of business processes. (Lourenço and Viegas (2016)) Level 3 classes are used to identify, describe and evaluate business processes while level 4 classes have an evaluation purpose, but only if there is a need to define a Administrative Conservation Period (PCA) and a Final Destination (DF) that was not previously defined in the level 3 class that is its parent. In short, PCA and DF may apply to 3rd or 4th level classes. The PCA is the period of time, recorded in years, during which information/documentation has to be maintained. The DF is the indication of the final destination of the information/documentation, after compliance with the PCA. The information/documentation may be fully or partially conserved, eliminated or simply not specified. The higher the level of a class the more information there will be about a class. This information is separated in 3 different components: • Class Description - present in all classes • Evaluation Context - present in level 3 classes • Evaluation Decisions - may be present in level 3 or level 4 classes The Class Description is a collection of attributes that describe the class. Some classes may have more or different attributes than others, particularly if they are level 3 or level 4 classes. The Evaluation Context is a set of fields with information about the actors, related business processes and legislation, which aims to frame assessment decisions. The Evaluation Decisions include the PCA and DF. If not present in a level 3 class when this class is the 9
parent of a level 4 class, then it should be present in that level 4 class. The following diagram illustrates the hierarchy of classes: Figure 4: Hierarchy of classes - Source da Costa Morango Teixeira (2020): adapted 3.2.2 Selection Tables Selection Tables (TS) are information management instruments used by entities, which allow organizing, structuring and aggregating information from the moment of its production/reception, and which constitute the sources of legitimacy for the evaluation, selection and elimination of public information. The TS of an entity identifies the processes that belong to that entity, for example, there are some specific health processes that don’t make sense to be associated to a school, like for example, a process about the hospitalization of a patient. Not all documents need to be conserved, so through their elimination it’s possible to make available the means and resources for the appropriate management and conservation of the documentation that needs to be preserved permanently (Alexandra Lourenço, Filipa Carvalho, Helena Neves and Rita Gago (2016)). Each TS is a subset of the Consolidated List with the minimum information about the classes and is published in Diário da República through a regulation. If we need more complete information about a class we should look into the Consolidated List. 10
A TS is constituted by (Alexandra Lourenço, Filipa Carvalho, Helena Neves and Rita Gago (2016)): • Identifying reference for each class • Title of the class (depending on the TS model, this may be expressed in one or two columns) • Description of the class (this element is not included in older TS models) • Administrative Conservation Period (PCA): The time period, recorded in years, during which the documents/information cannot be disposed of • Method for calculating the PCA: Instruction regarding the action or event that triggers the start of the conservation period. • Final Destination (DF): Indication of the final action for the documents/information once the PCA is completed. Options include permanent conservation (C), partial permanent conservation by sampling (CP) or destruction (E). • Entity responsible for ensuring the final disposition: identification of the entity (process owner) responsible for ensuring the permanent conservation of the information/documents (applies only to TS derived from the Consolidated List). There are 3 types of Selection Tables: The first one are the TS included in CLAV, derived from the Consolidated List, which are created and approved within CLAV without being published in Diário da República. The second one are the TS included in a document management regulation, derived from the Consolidated List and published in Diário da República. In the context of CLAV they are identified with the abbreviation ”PGD/LC”. The third one are the TS not derived from the Consolidated List that are included in document management regulations and published in Diário da República. In the context of CLAV, they are identified with the abbreviation ”PGD”. The CLAV platform includes a service for submitting elimination notices. For this service to be used, benefiting from assisted creation mechanisms, pre-validation, and automatic control and validation during submission, it was necessary to standardize the TS published over the past 30 years. 11
3.3 Science of Ontology Regarding the definition of ontology, Tom Gruber wrote the following entry (Liu and Özsu (2020)): ”In the context of computer and information sciences, an ontology defines a set of representational primitives with which to model a domain of knowledge or discourse. The representational primitives are typically classes (or sets), attributes (or properties), and relationships (or relations among class members). The definitions of the representational primitives include information about their meaning and constraints on their logically consistent application. In the context of database systems, ontology can be viewed as a level of abstraction of data models, analogous to hierarchical and relational models, but intended for modeling knowledge about individuals, their attributes, and their relationships to other individuals. Ontologies are typically specified in languages that allow abstraction away from data structures and implementation strategies; in practice, the languages of ontologies are closer in expressive power to first-order logic than languages used to model databases. For this reason, ontologies are said to be at the ”semantic” level, whereas database schema are models of data at the ”logical” or ”physical” level.” A W3C semantic web standard is Web Ontology Language (OWL) which is designed to represent rich and complex knowledge about things, a group of things and the relations between things. It’s based in a data model of triples named Resource Description Framework (RDF). RDF extends the linking structure of the Web to use URIs to name the relationship between things as well as the two ends of the link (this is usually referred to as a “triple”). This linking structure forms a directed, labeled graph, where the edges represent the named link between two resources, represented by the graph nodes (W3R (2014)). 12
18 new Vue({ 19 vuetify, 20 router, 21 store , 22 render: h => h(App) 23 }).$mount("#app"); 24 25 /* If we wanted to create another app instance then it would have the same configuration as App 1. */ 26 // App 2 27 /* 28 new Vue({ 29 vuetify, 30 router, 31 store , 32 render: h => h(App2) 33 }).$mount("#app2"); 34 */ Listing 5.1: Example of Vue 2 app initialization taken from CLAV. So to solve this problem Vue 3 now offers the concept of an app by calling ”createApp” which returns an app instance. Every app instance includes every API that globally mutates Vue’s behavior. The other APIs that don’t do that are now named exports. Creating a app is very simple in Vue 3: 1import { createApp } from 'vue' 2// const { createApp } = Vue // If using a CDN build of Vue 3 4const app = createApp({}) Listing 5.2: Simple example of app initialization in Vue 3. 19
The app instance can mount a root component and have it’s own components and directives without affecting other app instances: 1/** 2* main.ts 3* 4* Bootstraps Vuetify and other plugins then mounts the App 5*/ 6 7// Plugins 8import { registerPlugins } from '@/plugins' 9 10 // Components 11 import App from './App.vue' 12 13 // Composables 14 import { createApp } from 'vue' 15 16 // Bootstrap 17 import "bootstrap" 18 import "bootstrap/dist/css/bootstrap.min.css" 19 20 const app = createApp(App) 21 export const bus = app; 22 23 registerPlugins(app) 24 25 // If we wanted to add a component it wouldn't affect other app instances. 26 /* 27 app.component('button -counter', { 28 data: () => ({ 29 count: 0 30 }), 31 template: '<button @click="count++">Clicked {{ count }} times.</button >' 32 }) 33 */ 34 35 36 20
37 // If we wanted to add a directive it also wouldn't affect other apps. 38 /* 39 app.directive('focus ', { 40 mounted: (el) => el.focus() 41 }) 42 */ 43 44 // This app will be mounted to the page that has a "div" with id="app". 45 app.mount('#app') 46 // The rendered content of the mounted application will replace the inner HTML of the element passed to mount. Listing 5.3: More complete example of app initialization in Vue 3 taken from CLAV. If we want to share the same configuration between apps we can use a factory function: 1import { createApp } from 'vue' 2import App1 from './App1.vue' 3import App2 from './App2.vue' 4 5// Factory function. 6const createMyApp = (options) => { 7const app = createApp(options) 8// App1 and App2 will share the same directive. 9app.directive('focus' /* ... */) 10 11 return app 12 } 13 14 createMyApp(App1).mount('#app1') 15 createMyApp(App2).mount('#app2') Listing 5.4: Factory function example in order to share the same configuration between different apps in Vue 3. 21
5.2 Changes to the code 5.2.1 Options API vs Composition API coupled with SFCs Options API is the most commonly used API in Vue 2. Since Vue 2.7 a new API is available called Composition API. Below is an example of code using Vue 2 and Options API: 1<script > 2// ClassesArvoreLateral.vue 3export default { 4props: ["classeId"], 5data: () => ({ 6classesTree: [], 7indiceClasses: [], 8classesCarregadas: false , 9indiceCarregado: false , 10 search: null, 11 selectedParents: [] 12 }), 13 14 created: function() { 15 var levelIds = this.classeId.split("."); 16 var iteracoes = levelIds.length; 17 for (var i = 0; i < iteracoes; i++) { 18 levelIds.splice(levelIds.length - 1, 1); 19 this.selectedParents.push(levelIds.join(".")); 20 } 21 }, 22 23 mounted: async function() { 24 try { 25 var myClasses = await this.$request("get","/classes"); 26 var myIndice = await this.$request("get","/indicePesquisa"); 27 this.classesTree = await this.preparaTree(myClasses.data , myIndice. data); 28 this.classesCarregadas = true; 22
29 }catch (e) { 30 //console.log(e); 31 } 32 }, Listing 5.5: Example of Vue 2 with Options API from CLAV project. The recommended form to program in Vue 3 is to use Single-File Components (SFCs) together with the Composition API. The only difference is that you don’t need to use the ”export default” or the setup() function and you don’t need to return the declared variables and functions. Note that to make this simplification you have to write ”setup”, i.e. write <script setup> instead of just <script>. Here’s an example using Vue 3 and SFC + Composition API: 1<script setup > 2// ClassesArvore.vue 3import { defineProps , onMounted } from 'vue' 4import { host } from '@/config/global' 5import { useAppStore } from '@/store/app'; 6import treeview from "vue3 -treeview"; 7import "vue3 -treeview/dist/style.css"; 8 9const props = defineProps(["classeId"]) 10 const store = useAppStore() 11 12 var config = ref({}) 13 var nodes = ref({}) 14 var raizes = [] 15 16 var search = ref('') 17 var classesTree = [] 18 var classesCarregadas = false 19 var myClasses = [] 20 var myIndice = null 21 22 try { 23 await fetch(host + "/classes", { method: "GET", headers: { "Authorization ":"token " + store.token } }) 24 .then(response => response.json()) 25 .then(data => myClasses = data); 26 23
27 await fetch(host + "/indicePesquisa", { method: "GET", headers: { " Authorization":"token " + store.token } }) 28 .then(response => response.json()) 29 .then(data => myIndice = data); 30 31 classesTree = await preparaTree(myClasses , myIndice); 32 33 // Remover classes repetidas 34 const ids = classesTree.map(({ id }) => id); 35 classesTree = classesTree.filter(({ id }, index) => !ids.includes(id, index + 1)) 36 37 for (let i = 0; i < classesTree.length; i++) { 38 let classe = classesTree[i] 39 // Adicionar nó raíz. 40 raizes.push(classe.id) 41 // Adicionar filhos. 42 addTreeviewChildren(classe) 43 } 44 45 (...) 46 47 classesCarregadas = true; 48 }catch (e) { 49 console.log(e); 50 } 51 </script > Listing 5.6: Example of Vue 3 using Composition API and SFC from CLAV project. Additionally, lifecycle hooks are now prefixed with ”on”, for example onMounted, onCreated, onDeactivated, etc. Exposed methods/functions can be used as event handlers in the template as shown below: 1<template> 2<button @click="increment"> 3{{ level }} 4</button > 5</template> Listing 5.7: How to use a method inside a template in Vue 3, assuming that increment is a funtion. 24
5.2.2 Components Components are the core part of Vue and the main reason for utilizing this type of framework in projects. They allow for the composition and re-utilization of code as if it they were pieces. Stateful components are preferred over functional components in Vue 3 Functional components in Vue 2 have a better performance than stateful components due to it’s faster initialization and were used for their ability to return multiple root nodes. In Vue 3 the performance gain from using functional components is insignificant and stateful components can now return multiple root nodes, which means that stateful components are now the first choice for implementing components and functional components are only used to code simple components. Components don’t have to be registered anymore One of the first differences between Vue 2 and Vue 3 is that in Vue 2 it is mandatory to register the components while in Vue 3 that is not necessary anymore. Example in Vue 2 (Options API): 1// ConsultaClasse.vue 2<script > 3import ClassesFilho from "@/components/classes/consulta/ClassesFilho.vue"; 4import (...) // import other components 5 6// This option is not necessary in Vue 3. 7components: { 8ClassesFilho, 9Legislacao , 10 ClassesArvoreLateral, 11 (...) // other components. 12 }, 13 </script > 14 15 <template> 16 <ClassesFilho /> 17 <Legislacao /> 18 <ClassesArvoreLateral /> 19 (...) // other components. 20 </template> Listing 5.8: Components in Vue 2 using the Options API. 25
Example in Vue 3 (Composition API + SFC): 1// ConsultaClasse.vue 2<script setup > 3import ClassesFilho from "@/components/classes/consulta/ClassesFilho.vue"; 4import (...) // import other components 5</script > 6 7<template> 8<ClassesFilho /> 9<Legislacao /> 10 <ClassesArvoreLateral /> 11 (...) // other components. 12 </template> Listing 5.9: Components in Vue 3 using the Composition API and SFC. 5.2.3 Directives Directives in Vue are attributes that can be added to HTML nodes or components. Each directive serves its purpose and is very useful to make the frontend of an app more dynamic. Without the use of directives it makes no sense to use Vue other than re-utilizing code through components. Some directives received updates in Vue 3 which will be discussed below. v-model The v-model directive is used on components to implement a two-way data binding, that is to say that a parent component can send data and emit events to the child component as well as the child can send data and emit events to the parent component. Using this directive in Vue 2 was equal to passing a ”value” prop and emitting an ”input” event to a component: 1// ClassesArvoreLateral.vue (Parent Component) 2 3// Filter classes by code , title , notes , etc. 4<v-text-field v-model="search" /> // Child Component 5 6// Would be shorthand for: 26
7<v-text-field :value="search" @input="search = $event" /> Listing 5.10: v-model directive in Vue 2. Additionally, if we wanted to customize the prop or event names we would need to add a ”model” option to the child component making it mandatory to write code inside the child component. Here’s an example: 1// ChildComponent.vue 2<script > 3export default { 4model: { 5prop: 'searchValue', 6event: 'change' 7} 8} 9</script > Listing 5.11: Customization of v-model directive in Vue 2. Now v-model would be equal to a ”searchValue” prop and a ”change” event, instead of a ”value” prop and an ”input” event: 1<ChildComponent :searchValue="search" @change="search = $event" /> Listing 5.12: v-model directive in Vue 3. Sometimes we would need to pass data from the child to the parent component too (called a two-way data binding) so that the child could communicate to the parent an update to the ”search” prop like this: 1this.$emit('update:searchValue', newValue) Listing 5.13: Two-way data binding: from child to parent component, in Vue 2. And the parent could listen and update the prop like this: 1<v-text-field :searchValue.sync="search" /> 2 3<!-- would be shorthand for: --> 4 5<v-text-field :searchValue="search" @update:searchValue="search = $event" /> Listing 5.14: Two-way data binding: parent receiving from child component, in Vue 2. Now in Vue 3 it’s possible to code this two-way data binding more effectively and with less code, which means that the synchronization between parent and child components is done automatically, eliminating 27
the need of the ”.sync” modifier on the parent component. Instead of having a prop named ”value” and an event named ”input”, now it’s equivalent to ”modelValue” and ”update:modelValue” respectively: 1<v-text-field v-model="search" /> 2 3<!-- would be shorthand for: --> 4 5<v-text-field 6:modelValue="search" 7@update:modelValue="search = $event" 8/> Listing 5.15: Two-way data binding in Vue 3. There’s no need to have a ”model” component option anymore inside the child component as now it’s possible to customize the name of the prop directly in the directive’s argument. Take for example: 1<v-text-field v-model:searchValue="search" /> 2 3<!-- would be shorthand for: --> 4 5<v-text-field :searchValue="search" @update:searchValue="search = $event" /> Listing 5.16: ”model” component option removed in Vue 3. This also means that a component can now have multiple v-models: 1<v-text-field v-model:searchValue="search" v-model:charCount="count" /> 2 3<!-- would be shorthand for: --> 4 5<v-text-field 6:searchValue="search" 7@update:searchValue="search = $event" 8:charCount="count" 9@update:charCount="count = $event" 10 /> Listing 5.17: Multiple v-models made possible in Vue 3. 28
1<ParentComponent @fechar -dialogo="(n) => count += n" /> Listing 5.34: Parent component receives the ”Emits” arguments from its child, Vue 3. Or use a method as the event handler with the value being passed as the first parameter: 1<template> 2<ParentComponent @fechar -dialogo="fecharDialogo" /> 3</template> 4 5<script setup > 6function fecharDialogo(n) { 7count.value += n 8} 9</script > Listing 5.35: Alternative for the parent to receive ”Emits” arguments, Vue 3. 5.2.6 Computed Properties Computed Properties are used to avoid putting too much logic inside the template when working with reactive data. For example, instead of filtering an array in the template we can define a function to filter it and re-utilize this function to avoid the repetition of the same logic in the template. In Vue 2 Computed Properties are defined in the option ”computed” and each one is a written inside its own function: 1<script > 2// Noticias.vue 3export default { 4methods: { 5filtraOps: function (operacoes) { 6var filtered = []; 7for (var i = 0; i < operacoes.length; i++) { 8var levelsSet = new Set(); 9operacoes[i].level.forEach((l) => levelsSet.add(l)); 10 var levels = Array.from(levelsSet); 11 if (levels.includes(this.level)) { 12 filtered.push({ 13 label: operacoes[i].label , 14 url: operacoes[i].url, 15 level: operacoes[i].level , 35
16 }); 17 } 18 } 19 return filtered; 20 }, 21 } 22 23 computed: { 24 fops: function () { 25 return this.filtraOps(this.operacoes); 26 }, 27 </script > Listing 5.36: Computed Properties in Vue 2 using the Options API. In Vue 3 a Computed Property is a variable that holds a function: 1<script setup > 2// Noticias.vue 3function filtraOps(operacoes) { 4var filtered = []; 5for (var i = 0; i < operacoes.length; i++) { 6var levelsSet = new Set(); 7operacoes[i].level.forEach((l) => levelsSet.add(l)); 8var levels = Array.from(levelsSet); 9if (levels.includes(this.level)) { 10 filtered.push({ 11 label: operacoes[i].label , 12 url: operacoes[i].url, 13 level: operacoes[i].level , 14 }); 15 } 16 } 17 return filtered; 18 } 19 20 const fops = computed(() => { 21 return filtraOps(operacoes); 22 }) 36
23 </script > Listing 5.37: Computed Properties in Vue 3 using the Composition API and SFC. 5.2.7 Watchers Vue 2 vs Vue 3 While a computed property is used to calculate a direct result, a watcher is used when we want to manipulate the DOM or call a callback when there’s a change in the reactive state of some data due to the result of an asynchronous operation. Below is an example of the variable ”tabAtiva” that holds the name of the current active tab. When the user switches tabs the watcher calls the callback in order to update the value. 1<script > 2// MainPageHeader.vue 3export default { 4data() { 5return { 6tabAtiva: "CLAV", 7} 8}, 9 10 watch: { 11 "$route.meta.tabAtiva":function (newValue) { 12 this.tabAtiva = newValue; 13 }, 14 }, 15 } 16 17 </script > Listing 5.38: Watcher in Vue 2 using the Options API. With the Composition API we can use the watch function to trigger a callback whenever the state of something changes: 1<script setup > 2// MainPageHeader.vue 3var tabAtiva = ref("CLAV") 4 5watch(tabAtiva , (newValue) => { 6tabAtiva.value = newValue; 37
7}) 8</script > Listing 5.39: Watcher in Vue 3 using the Composition API and SFC. Watch on Arrays In Vue 3 when watching an array the callback doesn’t trigger on mutation anymore, only when the array is replaced. To bypass this the ”deep” option is mandatory: 1// ClassesArvore.vue 2watch(nodes , (newValue , oldValue) => { 3Object.entries(newValue).forEach(([key , value]) => { 4if (value.state.opened == true) { 5formatTreeviewNodes() 6} 7}) 8}, {deep: true}); // Mandatory in order to trigger callback on mutation. Listing 5.40: Watching arrays in Vue 3 is different. The ”deep” option must be specified. 5.2.8 Nested Objects Nested Objects can be objects or arrays defined inside a reactive object. In Vue, the state of objects or arrays that are contained within a reactive object are naturally mutable which means these mutations will be detected automatically: 1export default { 2data() { 3return { 4obj: { 5nested: { num: 99 }, 6entidades: ['AAN','AC'] 7}}}, 8methods: { 9mutateDeeply() { 10 this.obj.nested.num-- 11 this.obj.entidades.push('A3ES') 12 }}} Listing 5.41: Nested Object in Vue 2 using the Options API. 38
Example in Vue 3 (SFC + Composition API): 1<script setup > 2const nestedObj = ref({ 3nested: {num: 99}, 4entidades: ['AAN','AC'] 5}) 6 7function mutateDeeply() { 8nestedObj.value.nested.num-- 9nestedObj.value.entidades.push('A3ES') 10 } 11 </script > Listing 5.42: Nested Object in Vue 3 using the Composition API and SFC. 5.2.9 SFC State-driven CSS Variables SFC <style> tags allow you to connect CSS values to dynamic component states by using the v-bind CSS function. You can also use JavaScript expressions within them but these must be enclosed in quotation marks. With the following code each type 1 header is written in the color defined on the script instead of defining it on the CSS. 1<template> 2<h1>CLAV </h1> 3</template> 4 5<script setup > 6import { ref } from 'vue' 7const theme = ref({ 8color: 'blue', 9}) 10 </script > 11 12 <style scoped > 13 h1 { 14 color: v-bind('theme.color'); 15 } 39
16 </style > Listing 5.43: Dynamic use of Vue 3 CSS variables - defining the header color on the script. The real value is transformed into a hashed CSS custom property which keeps the CSS static. This custom property is then added to the root element of the component through inline styles and it updates automatically whenever the original value changes. 5.2.10 Vuetify The first change a programmer should make when upgrading to Vuetify 3 from Vuetify 2 is updating the setup of Vuetify. The Vuetify class was used in Vuetify 2: 1// main.ts 2import Vuetify from "vuetify/lib"; 3 4Vue.use(Vuetify) 5 6const vuetify = new Vuetify({ ... }) 7 8const app = new Vue({ 9vuetify, 10 ... 11 }) Listing 5.44: Vuetify import when initiating the app using Vuetify 2 and Vue 2 in CLAV. Now the function createVuetify() is used in Vuetify 3: 1// main.ts 2import { createVuetify } from 'vuetify' 3 4// Components 5import App from './App.vue' 6const app = createApp(App) 7 8const vuetify = createVuetify({ ... }) 9 40
10 app.use(vuetify) Listing 5.45: Vuetify function used to import Vuetify 3 in Vue 3 in CLAV. There are other small details in Vuetify 3 such as text colors having a ”text-” prefix, for example in Vuetify 2 we would write ”.white–text” and now in Vuetify 3 we write ”.text-white”. All this details can be found on the Vuetify upgrade guide. 5.3 Changes in Vue’s router The router is used to define routes for the application. Each route must have a path, an unique name and a simple component associated with it. This component only needs to include the components that will compose the page and the less logic possible. In Vue 3, the way to program the router remains the same but there are some significant changes between the v3 router (from Vue 2) and the v4 router (from Vue 3). 5.3.1 Router creation, access and routes definition. 1// router.ts 2import Vue from "vue"; 3import Router from "vue-router"; 4 5Vue.use(Router); 6 7export default new Router({ 8mode: "history", 9base: process.env.BASE_URL , 10 routes: [ 11 { 12 path: "/", 13 name: "home", 14 component: () => import("./views/Home.vue"), 15 meta: { levels: [0, 1, 2, 3, 3.5, 4, 5, 6, 7], tabAtiva: "CLAV", ent: true} 16 }, 17 ] 18 }) 41
19 // The router can be accessed in a component's script through $router. Listing 5.46: Router in Vue 2. In Vue 3 the router is exposed as a variable created with a function with parameters such as ”history” and ”routes”: 1// router/index.js 2import { createRouter , createWebHistory } from 'vue-router' 3 4const routes = [ 5{ 6path: "/", 7name: "home", 8component: () => import("@/pages/index.vue"), 9meta: {levels: [0,1,2,3,4,5,6,7], tabAtiva: "CLAV", ent: true} 10 }, 11 ] 12 13 const router = createRouter({ 14 history: createWebHistory(process.env.BASE_URL), 15 routes, 16 }) 17 18 export default router 19 // The router can be used in a component's script like this: import router from '@/router' Listing 5.47: Router in Vue 3. 5.3.2 Other significant changes in the router • The routes property is now mandatory in the router options. • Pushing or resolving a route with a name that doesn’t exist throws an error: 1router.push({ name: 'autenticacaoo' }) // throws error 2router.resolve({ name: 'autenticacaoo' }) // throws error Listing 5.48: Error thrown when resolving a route that doesn’t exist in Vue 3. Previously, the router would navigate to / but not display anything (in place of the main page). Throwing an error makes more sense because we can’t produce a valid URL to navigate to. 42
• For the same reason, pushing or resolving a named route without its required parameters will throw an error: 1// given the following route with the "idClasse" as a parameter: 2const routes = [{ path: '/classes/consultar/:idClasse', name: ' consultaClasse', component: ClassesConsulta }] 3 4// ‘’idClasse parameter is missing so the following will fail: 5router.push({ name: 'consultaClasse' }) // throws error 6router.resolve({ name: 'consultaClasse' }) // throws error Listing 5.49: Parameters must be specified if they’re defined in the route, Vue 3. • Named child routes with empty path no longer append a slash: 1const routes = [ 2{ 3path: '/classes/consultar', 4name: 'classes', 5component: Classes , 6children: [ 7{ path: '', name: 'filhos_classe', component: FilhosClasse }, 8], 9}, 10 ] Listing 5.50: No slash at the end for named child routes, Vue 3. For example, navigating or resolving to the route named ’filhos-classe’ will produce an URL without a slash at the end (’/filhos_classe’): 1router.resolve({ name: 'filhos_classe' }).href Listing 5.51: URL is simplified for named child routes, Vue 3. This has an important side effect on the children’s redirect records: 1const routes = [ 2{ 3path: '/classes/consultar', 4component: Classes , 5children: [ 6{ path: '', redirect: 'filhos' }, 43
7], 8}, 9] 10 // Now redirects to '/filhos' instead of '/classes/consultar/filhos' Listing 5.52: Redirecting becomes different for child routes, Vue 3. This feature exists to make trailing slash behavior consistent: by default all routes allow a trailing slash. This can be disabled using the ”strict” option and manually appending (or not) a forward slash to the routes. • TypeScript changes: To make the types more consistent and expressive some of the types were renamed: Vue 2 (vue-router@3) Vue 3 (vue-router@4) RouteConfig RouteRecordRaw Location RouteLocation Route RouteLocationNormalized Table 1: Types used in Vue 2 router vs. Vue 3 router. 44
6.4 List of Classes Interface This page is loaded when clicking ”Lista Consolidada” in the operations list. As said before, it shows a description of what it is and also what the user can do. When clicking the button at the bottom of the text it will load the list of classes. Figure 16: Description of what is the List of Classes. The following image shows the List of Classes (also called processes) made with the third party treeview plugin. All the classes are loaded with the help from the API which gets them from the GraphDB backend. At the left of each classes there is an arrow that when clicked will expand or condense the tree. When clicking the number or title of a class the user will be directed to a page with information about that class. Figure 17: List of classes represented in a tree format. 51
Each class has different levels which represent the level of depth the tree of a class can have. For example the class 200 is a class of level 1 whereas 200.10 is a level 2 class, 200.10.002 is level 3 and 200.10.002.01 is level 4. The higher the level of a class the more information there will be about a class. Every class has its description but level 1 and level 2 classes have only a description with some attributes. Level 3 classes offer a description, an evaluation context and may have evaluation decisions. Level 4 classes offer a description and evaluation decisions. The class description includes the state of the class (active or inactive), a description, application notes and exclusion notes. This is what is presented to the user when clicking a level 1 class: Figure 18: Description of a level 1 class. Every page that presents information about a class has links to other classes, entities and legislations in order to facilitate the user’s navigation on the website. 52
Each attribute has an info button which shows some information about the attribute: Figure 19: Information about an attribute of a class. This is what is presented to the user when clicking a level 2 class: Figure 20: Level 2 class. 53
This is what is presented to the user when clicking a level 3 class: Figure 21: Level 3 class with tabs closed. As said before, level 3 and level 4 classes are more complex with more details. The evaluation context shows the type of process, indicates if the process is transversal or not, presents the entities that own the process, the entities that participate in the process, related processes and legislation. This is what is presented to the user when clicking on the evaluation context tab: Figure 22: Evaluation context tab of a level 3 class. The evaluation decisions indicates the number of years that the documentation should be preserved for, the way of counting that period of time and the justification for having that time. It also has the final destination for the class for when that time is over, some classes may be preserved in their final stage for example, and the justification for that final destination. 54
This is what is presented to the user when clicking on the evaluation decisions tab: Figure 23: Evaluation decisions tab of a level 3 class. Level 3 classes also have more information in the description of the class tab than other classes of a different level. Finally, this is what is presented to the user when clicking a level 4 class: Figure 24: Level 4 class. 55
6.5 Selection Tables Interface Selection Tables (TS) are information management instruments used by entities, which allow organizing, structuring and aggregating information from the moment of its production/reception, and which constitute the sources of legitimacy for the evaluation, selection and elimination of public information. Each TS is a subset of the List of Classes and is published in Diário da República through a regulation. Each TS has the minimum information about the classes. If we need more complete information about a class we should look into the List of Classes. Figure 25: Description of what are Selection Tables. Selection Tables have 3 different types: TS inserted in CLAV, TS acquired from the list of classes and TS that aren’t acquired from the list of classes. Figure 26: The 3 types of Selection Tables. 56
At the moment there are no TS inserted in CLAV: Figure 27: Selection Tables inserted in CLAV. There are 4 TS that come from the list of classes: Figure 28: Selection Tables from the list of classes. 57
And 64 TS that don’t come from the list of classes: Figure 29: Selection Tables from another source. In the end of each row there are 2 buttons. The PDF button will direct the user to a pdf file in Diário da República while the button with an eye will direct the user to a page in CLAV to show the details of the corresponding selection table. For each tab there is an info button that gives a detailed explanation about each type of TS: Figure 30: Information about the TS that come from classes. 58
6.6 List of Entities Interface The entities are included in the information about classes when consulting them and are normally associated with them. The list of entities is the ”catalog of public entities that intervene in business processes (3rd level classes of the Consolidated List). They can integrate one or more types of entities.” The following page informs the user about what are entities and what operations can be done with them. Figure 31: Description of what is the list of entities. The list of entities can be consulted in a table: Figure 32: List of entities. 59
Where you can perform a search: Figure 33: A search for the word ”minho” that shows all the entities that include that word. 6.7 List of Typologies of Entities Interface Typologies of entities are included only in level 3 classes and are basically what defines a group of entities. The following page presents a brief definition about it and the operations that can be performed. Figure 34: Description of what is the list of typologies of entities. The list of typologies can be consulted in a table. Each typology has only an acronym and its name: Figure 35: List of typologies. 60