Friday, April 9, 2021

Reactivity In Vue

 Reactivity is the ability for a variable (array, string, number, object, etc) to update when its value or any other variable that it makes reference to is changed after declaration.


In this article, we’re going to look at reactivity in Vue, how it works, and how we can create reactive variables using newly created methods and functions. This article is targeted at developers who have a good understanding of how Vue 2.x works and are looking to get familiar with the new Vue 3.

We’re going to build a simple application to better understand this topic.

By default, JavaScript isn’t reactive. This means that if we create the variable boy and reference it in part A of our application, then proceed to modify boy in part B, part A will not update with the new value of boy.

let framework = 'Vue';
let sentence = `${framework} is awesome`;
 // logs "Vue is awesome"
framework = 'React';
//should log "React is awesome" if 'sentence' is reactive.

The snippet above is a perfect example of the non-reactive nature of JavaScript — hence, why the change isn’t reflected in the sentence variable.

In Vue 2.x, props, computed, and data() were all reactive by default, with the exception of properties that are not present in data when such components are created. This means that when a component is injected into the DOM, only the existing properties in the component’s data object would cause the component to update if and when such properties change.

Internally, Vue 3 uses the Proxy object (an ECMAScript 6 feature) to ensure that these properties are reactive, but it still provides the option to use Object.defineProperty from Vue 2 for Internet Explorer support (ECMAScript 5). This method defines a new property directly on an object, or modifies an existing property on an object, and returns the object.

At first glance and since most of us already know that reactivity is not new in Vue, it might seem unnecessary to make use of these properties, but the Options API has its limitations when you’re dealing with a large application with reusable functions in several parts of the application. To this end, the new Composition API was introduced to help with abstracting logic in order to make a code base easier to read and maintain. Also, we can now easily make any variable reactive regardless of its data type using any of the new properties and methods.

When we use the setup option, which serves as the entry point for the Composition API, the data object, computed properties, and methods are inaccessible because the component instance has not yet been created when setup is executed. This makes it impossible to take advantage of the built-in reactivity in any of these features in setup. In this tutorial, we’re going to learn about all of the ways we can do this.

The Reactive Method

According to the documentation, the reactive method, which is the equivalent of Vue.observable() in Vue 2.6, can be useful when we’re trying to create an object all of whose properties are reactive (such as the data object in the Options API). Under the hood, the data object in the Options API uses this method to make all of the properties in it reactive.

But we can create our own reactive object like this:

import { reactive } from 'vue'

// reactive state
let user = reactive({
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "",
        "address": {
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "city": "Gwenborough",
            "zipcode": "92998-3874",
            "geo": {
                "lat": "-37.3159",
                "lng": "81.1496"
        "phone": "1-770-736-8031 x56442",
        "website": "",
        "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
        "cars": {
            "number": 0

Here, we imported the reactive method from Vue, and then we declared our user variable by passing its value to this function as an argument. In doing so, we’ve made user reactive, and, thus, if we use user in our template and if either the object or a property of this object should change, then this value will get automatically updated in this template.


Just as we have a method for making objects reactive, we also need one to make other standalone primitive values (strings, booleans, undefined values, numbers, etc.) and arrays reactive. During development, we would work with these other data types while also needing them to be reactive. The first approach we might think of would be to use reactive and pass in the value of the variable that we want to make reactive.

import { reactive } from 'vue'

const state = reactive({
  users: [],

Because reactive has deep reactive conversion, user as a property would also be reactive, thereby achieving our goal; hence, user would always update anywhere it is used in the template of such an app. But with the ref property, we can make any variable with any data type reactive by passing the value of that variable to ref. This method also works for objects, but it nests the object one level deeper than when the reactive method is used.

let property = {
  rooms: '4 rooms',
  garage: true,
  swimmingPool: false
let reactiveProperty = ref(property)
// prints {
// value: {rooms: "4 rooms", garage: true, swimmingPool: false}
// }

Under the hood, ref takes this argument passed to it and converts it into an object with a key of value. This means, we can access our variable by calling variable.value, and we can also modify its value by calling it in the same way.

import {ref} from 'vue'
let age = ref(1)

//prints 1
//prints 2

With this, we can import ref into our component and create a reactive variable:

  <div class="home">
    <form @click.prevent="">
          <th>Edit Cars</th>
        <tr v-for="user in users" :key="">
          <td>{{ }}</td>
          <td>{{ user.username }}</td>
          <td>{{ }}</td>
              style="width: 20px;"
            <cars-number :cars="" />
      <p>Total number of cars: {{ getTotalCars }}</p>
  // @ is an alias to /src
  import carsNumber from "@/components/cars-number.vue";
  import axios from "axios";
  import { ref } from "vue";
  export default {
    name: "Home",
    data() {
      return {};
    setup() {
      let users = ref([]);
      const getUsers = async () => {
        let { data } = await axios({
          url: "data.json",
        users.value = data;
      return {
    components: {
    created() {
    computed: {
      getTotalCars() {
        let users = this.users;
        let totalCars = users.reduce(function(sum, elem) {
          return sum +;
        }, 0);
        return totalCars;

Here, we imported ref in order to create a reactive users variable in our component. We then imported axios to fetch data from a JSON file in the public folder, and we imported our carsNumber component, which we’ll be creating later on. The next thing we did was create a reactive users variable using the ref method, so that users can update whenever the response from our JSON file changes.

We also created a getUser function that fetches the users array from our JSON file using axios, and we assigned the value from this request to the users variable. Finally, we created a computed property that computes the total number of cars that our users have as we have modified it in the template section.

It is important to note that when accessing ref properties that are returned in the template section or outside of setup(), they are automatically shallow unwrapped. This means that refs that are an object would still require a .value in order to be accessed. Because users is an array, we could simply use users and not users.value in getTotalCars.

In the template section, we displayed a table that displays each user’s information, together with a <cars-number /> component. This component accepts a cars prop that is displayed in each user’s row as the number of cars they have. This value updates whenever the value of cars changes in the user object, which is exactly how the data object or computed property would work if we were working with the Options API.



When we use the Composition API, the setup function accepts two arguments: props and context. This props is passed from the component to setup(), and it makes it possible to access the props that the component has from inside this new API. This method is particularly useful because it allows for the destructuring of objects without losing its reactivity.

  <p>{{ cars.number }}</p>
  export default {
    props: {
      cars: {
        type: Object,
        required: true,
      gender: {
        type: String,
        required: true,
    setup(props) {
   // prints {gender: "female", cars: Proxy}

To use a value that is an object from props in the Composition API while ensuring it maintains its reactivity, we make use of toRefs. This method takes a reactive object and converts it into a plain object in which each property of the original reactive object becomes a ref. What this means is that the cars prop…

cars: {
  number: 0

… would now become this:

  value: cars: {
    number: 0

With this, we can make use of cars inside any part of the setup API while still maintaining its reactivity.

 setup(props) {
      let { cars } = toRefs(props);
      // prints {number: 0}

We can watch this new variable using the Composition API’s watch and react to this change however we might want to.

setup(props) {
      let { cars } = toRefs(props);
        () => cars,
        (cars, prevCars) => {
          console.log("deep ", cars.value, prevCars.value);
        { deep: true }


Another common use case we could be faced with is passing a value that is not necessarily an object but rather one of the data types that work with ref (array, number, string, boolean, etc.). With toRef, we can create a reactive property (i.e. ref) from a source reactive object. Doing this would ensure that the property remains reactive and would update whenever the parent source changes.

const cars = reactive({
  Toyota: 1,
  Honda: 0

const NumberOfHondas = toRef(state, 'Honda')

console.log(state.Honda) // 1

console.log(NumberOfHondas.value) // 2

Here, we created a reactive object using the reactive method, with the properties Toyota and Honda. We also made use of toRef to create a reactive variable out of Honda. From the example above, we can see that when we update Honda using either the reactive cars object or NumberOfHondas, the value gets updated in both instances.

This method is similar and yet so different from the toRefs method that we covered above in the sense that it maintains its connection to its source and can be used for strings, arrays, and numbers. Unlike with toRefs, we do not need to worry about the existence of the property in its source at the time of creation, because if this property does not exist at the time that this ref is created and instead returns null, it would still be stored as a valid property, with a form of watcher put in place, so that when this value changes, this ref created using toRef would also be updated.

We can also use this method to create a reactive property from props. That would look like this:

  <p>{{ cars.number }}</p>
  import { watch, toRefs, toRef } from "vue";
  export default {
    props: {
      cars: {
        type: Object,
        required: true,
      gender: {
        type: String,
        required: true,
    setup(props) {
      let { cars } = toRefs(props);
      let gender = toRef(props, "gender");
        () => cars,
        (cars, prevCars) => {
          console.log("deep ", cars.value, prevCars.value);
        { deep: true }

Here, we created a ref that would be based on the gender property gotten from props. This comes in handy when we want to perform extra operations on the prop of a particular component.


In this article, we have looked at how reactivity in Vue works using some of the newly introduced methods and functions from Vue 3. We started by looking at what reactivity is and how Vue makes use of the Proxy object behind the scenes to achieve this. We also looked at how we can create reactive objects using reactive and how to create reactive properties using ref.

Finally, we looked at how to convert reactive objects to plain objects, each of whose properties are a ref pointing to the corresponding property of the original object, and we saw how to create a ref for a property on a reactive source object.

Further Resources



Sunday, February 21, 2021

A few questions worth noticing about MySQL


1. What is MySQL? 

MySQL is an open source DBMS which is built, supported and distributed by MySQL AB (now acquired by Oracle)

2. What are the technical features and technical specifications of MySQL? 

MySQL database software is a client or server system which includes features:

  • Multithreaded SQL server supporting various client programs and libraries
  • Different backend
  • Wide range of application programming interfaces and
  • Administrative tools.

And technical specifications:

  • Flexible structure
  • High performance
  • Manageable and easy to use
  • Replication and high availability
  • Security and storage management
  • Drivers
  • Graphical Tools
  • MySQL Enterprise Monitor
  • MySQL Enterprise Security
  • JSON Support
  • Replication & High-Availability
  • Manageability and Ease of Use
  • OLTP and Transactions
  • Geo-Spatial Support

3. Why do we use the MySQL database server?

MySQL database server is reliable, fast and very easy to use.  This software can be downloaded as freeware and can be downloaded from the internet.

4. What are Heap tables?

HEAP tables are present in memory and they are used for high speed storage on temporary


• BLOB or TEXT fields are not allowed

• Only comparison operators can be used =, <,>, = >,=<

• AUTO_INCREMENT is not supported by HEAP tables

• Indexes should be NOT NULL

5. What is the default port for MySQL Server?

The default port for MySQL server is 3306.

6. What are the advantages of MySQL when compared with Oracle? 

  • MySQL is open source software which is available at any time and has no cost involved.
  • MySQL is portable
  • GUI with command prompt.
  • Administration is supported using MySQL Query Browser

7. Differentiate between FLOAT and DOUBLE? 

Following are differences for FLOAT and DOUBLE:

• Floating point numbers are stored in FLOAT with eight place accuracy and it has four bytes.

• Floating point numbers are stored in DOUBLE with accuracy of 18 places and it has eight bytes.

8. In which language MySQL has been written?

MySQL is written in C and C++, and its SQL parser is written in yacc.

9. How to represent ENUMs and SETs internally? 

ENUMs and SETs are used to represent powers of two because of storage optimizations.

10. What is the usage of ENUMs in MySQL?

ENUM is a string object used to specify set of predefined values and that can be used during table creation.

 Create table size(name ENUM('Small', 'Medium','Large'); 

11. Define REGEXP? 

REGEXP is a pattern match in which  matches pattern anywhere in the search value.

12. Difference between CHAR and VARCHAR? 

Following are the differences between CHAR and VARCHAR:

  • CHAR and VARCHAR types differ in storage and retrieval
  • CHAR column length is fixed to the length that is declared while creating table. The length value ranges from 1 and 255
  • When CHAR values are stored then they are right padded using spaces to specific length. Trailing spaces are removed when CHAR values are retrieved.

13. Give string types available for column?

The string types are:

  • SET
  • BLOB
  • ENUM
  • CHAR
  • TEXT

14. How to get current MySQL version?


is used to get the current version of MySQL.

15. What storage engines are used in MySQL? 

Storage engines are called table types and data is stored in files using various techniques.

Technique involves:

  • Storage mechanism
  • Locking levels
  • Indexing
  • Capabilities and functions.

16. What are the drivers in MySQL?

Following are the drivers available in MySQL:

  • PHP Driver
  • JDBC Driver
  • ODBC Driver
  • PYTHON Driver
  • PERL Driver
  • RUBY Driver
  • CAP11PHP Driver
  • Ado.net5.mxj

17. What does a TIMESTAMP do on UPDATE CURRENT_TIMESTAMP data type?

TIMESTAMP column is updated with Zero when the table is created.  UPDATE CURRENT_TIMESTAMP modifier updates the timestamp field to current time whenever there is a change in other fields of the table.

18. What is the difference between primary key and candidate key?

Every row of a table is identified uniquely by primary key. There is only one primary key for a table.

Primary Key is also a candidate key. By common convention, candidate key can be designated as primary and which can be used for any foreign key references.

19. How do you login to MySql using Unix shell?

We can login through this command:

# [mysql dir]/bin/mysql -h hostname -u <UserName> -p <password>

20. What does myisamchk do?

It compress the MyISAM tables, which reduces their disk or memory usage.

21. How do you control the max size of a HEAP table?

Maximum size of Heal table can be controlled by MySQL config variable called max_heap_table_size.

22. What is the difference between MyISAM Static and MyISAM Dynamic?

In MyISAM static all the fields will have fixed width. The Dynamic MyISAM table will have fields like TEXT, BLOB, etc. to accommodate the data types with various lengths.

MyISAM Static would be easier to restore in case of corruption.

23. What are federated tables?

Federated tables which allow access to the tables located on other databases on other servers.

24. What, if a table has one column defined as TIMESTAMP?

Timestamp field gets the current timestamp whenever the row gets altered.

25. What happens when the column is set to AUTO INCREMENT and if you reach maximum value in the table?

It stops incrementing. Any further inserts are going to produce an error, since the key has been used already.

26. How can we find out which auto increment was assigned on Last insert?

LAST_INSERT_ID will return the last value assigned by Auto_increment and it is not required to specify the table name.

27. How can you see all indexes defined for a table?

Indexes are defined for the table by:

SHOW INDEX FROM <tablename>;

28. What do you mean by % and _ in the LIKE statement?

% corresponds to 0 or more characters, _ is exactly one character in the LIKE statement.

29. How can we convert between Unix & MySQL timestamps?

UNIX_TIMESTAMP is the command which converts from MySQL timestamp to Unix timestamp

FROM_UNIXTIME is the command which converts from Unix timestamp to MySQL timestamp.

30. What are the column comparisons operators?

The = , <>, <=, <, >=, >,<<,>>, <=>, AND, OR, or LIKE operators are used in column comparisons in SELECT statements.

31. How can we get the number of rows affected by query?

Number of rows can be obtained by

 SELECT COUNT (user_id) FROM users;

32.  Is Mysql query is case sensitive?


SELECT VERSION(), CURRENT_DATE;SeLect version(), current_date;seleCt vErSiOn(), current_DATE; 

All these examples are same. It is not case sensitive.

33. What is the difference between the LIKE and REGEXP operators?  

LIKE and REGEXP operators are used to express with ^ and %.

SELECT * FROM employee WHERE emp_name REGEXP "^b";SELECT * FROM employee WHERE emp_name LIKE "%b"; 

34. What is the difference between BLOB AND TEXT?

A BLOB is a binary large object that can hold a variable amount of data. There are four types of BLOB –

  • BLOB

They all differ only in the maximum length of the values they can hold.

A TEXT is a case-insensitive BLOB. The four TEXT types

  • TEXT

They all correspond to the four BLOB types and have the same maximum lengths and storage requirements.

The only difference between BLOB and TEXT types is that sorting and comparison is performed in case-sensitive for BLOB values and case-insensitive for TEXT values.

35. What is the difference between mysql_fetch_array and mysql_fetch_object?

Following are the differences between mysql_fetch_array and mysql_fetch_object:

mysql_fetch_array() -Returns a result row as an associated array or a regular array from database.

mysql_fetch_object –  Returns a result row as object from database.

36. How can we run batch mode in mysql?

Following commands are used to run in batch mode:

 mysql ;mysql mysql.out

37. Where MyISAM table will be stored and also give their formats of storage?

Each MyISAM table is stored on disk in three formats:

  • The ‘.frm’ file stores the table definition
  • The data file has a ‘.MYD’ (MYData) extension
  • The index file has a ‘.MYI’ (MYIndex) extension

38. What are the different tables present in MySQL?

Total 5 types of tables are present:

  • MyISAM
  • Heap
  • Merge
  • ISAM

MyISAM is the default storage engine as of MySQL .

39. What is ISAM?

ISAM  is abbreviated as Indexed Sequential Access Method.It was developed by IBM to store and retrieve data on secondary storage systems like tapes.

40. What is InnoDB?

lnnoDB is a transaction safe storage engine developed by Innobase Oy which is a Oracle Corporation now.

41. How MySQL Optimizes DISTINCT?

DISTINCT is converted to a GROUP BY on all columns and it will be combined with ORDER BY clause.

 SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a;

42. How to enter Characters as HEX Numbers?

If you want to enter characters as HEX numbers, you can enter HEX numbers with single quotes and a prefix of (X), or just prefix HEX numbers with (Ox).

A HEX number string will be automatically converted into a character string, if the expression context is a string.

43. How to display top 50 rows?

In MySql, top 50 rows are displayed by using this following query:


44. How many columns can be used for creating Index?

Maximum of 16 indexed columns can be created for any standard table.

45. What is the different between NOW() and CURRENT_DATE()?

NOW () command is used to show current year,month,date with hours,minutes and seconds.

CURRENT_DATE() shows current year,month and date only.

46. What are the objects can be created using CREATE statement?

Following objects are created using CREATE statement:

  • USER
  • VIEW

47. How many TRIGGERS are allowed in MySql table?

SIX triggers are allowed in MySql table. They are as follows:


48. What are the nonstandard string types?

Following are Non-Standard string types:

  • TEXT

49. What are all the Common SQL Function?

CONCAT(A, B) – Concatenates two string values to create a single string output. Often used to combine two or more fields into one single field.

FORMAT(X, D) – Formats the number X to D significant digits.

CURRDATE(), CURRTIME() – Returns the current date or time.

NOW() – Returns the current date and time as one value.

MONTH(), DAY(), YEAR(), WEEK(), WEEKDAY() – Extracts the given data from a date value.

HOUR(), MINUTE(), SECOND() – Extracts the given data from a time value.

DATEDIFF(A, B) – Determines the difference between two dates and it is commonly used to calculate age

SUBTIMES(A, B) – Determines the difference between two times.

FROMDAYS(INT) – Converts an integer number of days into a date value.

50. Explain Access Control Lists.

An ACL (Access Control List) is a list of permissions that is associated with an object. This list is the basis for MySQL server’s security model and it helps in troubleshooting problems like users not being able to connect.

MySQL keeps the ACLs (also called grant tables) cached in memory. When a user tries to authenticate or run a command, MySQL checks the authentication information and permissions against the ACLs, in a predetermined order.

51. Differentiate CHAR_LENGTH and LENGTH?

CHAR_LENGTH  is character count whereas the LENGTH is byte count. The numbers are same for Latin characters but they are different for Unicode and other encodings.

52. What is the difference between TRUNCATE and DELETE in MySQL?

TRUNCATE is a DDL command, DELETE is a DML command.

It is not possible to use Where command with TRUNCATE but you can use it with DELETE command.

TRUNCATE cannot be used with indexed views whereas DELETE can be used with indexed views.

The DELETE command is used to delete data from a table. It only deletes the rows of data from the table while, truncate is very dangerous command and should be used carefully because it deletes every row permanently from a table.

53. How to get the current date in MySQL?

To get current date, use the following syntax:


54. How to display Nth highest salary from a table in a MySQL query?

Let us take a table named the employee.

To find Nth highest salary is:

select distinct(salary)from employee order by salary desc limit n-1,1

if you want to find 3rd largest salary:

select distinct(salary)from employee order by salary desc limit 2,1

55. What is the difference between NOW() and CURRENT_DATE()?

NOW() command is used to show current year, month, date with hours, minutes and seconds while CURRENT_DATE() shows the current year with month and date only.

56. Write a query to display current date and time?

If you want to display current date and time, use –


If you want to display current date only, use:


57. How can you validate emails using a single query?

To validate emails you can use the function of the regular expression (REGEXP_LIKE). Consider the below query.

where NOT REGEXP_LIKE(Email, ‘[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}’, ‘i’);

58. What is the main difference between ‘BETWEEN’ and ‘IN’ condition operators?

BETWEEN operator is used to display rows based on a range of values in a row whereas the IN condition operator is used to check for values contained in a specific set of values.

Example of BETWEEN:

SELECT * FROM Students where ROLL_NO BETWEEN 10 AND 50;

Example of IN:

SELECT * FROM students where ROLL_NO IN (8,15,25);

59. How can you calculate the sum of any column of a table?

SELECT SUM(price) as total FROM products;

60. What IFNULL() statement is used for in MySQL?

The Query in MySQL can be written precisely using IFNULL() statement. The IFNULL() statement test its first argument and returns if it’s not NULL, or returns its second argument, otherwise.

mysql> SELECT name, IFNULL(id,'Unknown') AS 'id' FROM taxpayer;

| name 	  | id      | 
| bernina | 198-48  | 
| bertha  | Unknown | 
| ben     | Unknown | 
| bill    | 475-83  | 

61. How will you export tables as an XML file in MySQL?

We use ‘-e‘ (export) option to export MySQL table or the whole database into an XML file. With large tables we may need to implement it manually but for small tables, applications like phpMyAdmin can do the job.

A native command of MySQL can do it.

mysql -u USER_NAME –xml -e 'SELECT * FROM table_name' > table_name.xml