Gizzy Berry

Gizzy Berry

1573269337

A Beginner’s Guide to Vue 3 Composition API with Examples

Vue introduces Composition API (Function-based API) as an addition to current Options-based API. The API will be released with Vue 3, but now you can try it with Vue 3 Composition API added to your Vue 2 app. In this tutorial, we’re gonna show you:

  • New Vue Composition API overview and comparison with classic Vue Options-based API
  • Examples to implement a Vue Component with new API: props, data, watchers, lifecycle hooks
  • Example to take advantage of new Vue 3 Composition API (function-based API): split Topics into Functions

Contents

What’s changed when Vue Composition API is added?

Everything will still work as it works before. Almost things don’t change:

  • CLI
  • Template syntax
  • Object format
  • Reactivity system
  • Concepts of computed properties, watchers & component lifecycle
  • SFC format
  • Progressive nature of Vue framework

Options-based API vs Composition API

The difference of current Options-based API concept vs new Composition API (Function-based API) concept is the way we think of what a component contains:

  • Options-based API: A component contains types of properties/methods/options.
  • Composition API: A component encapsulates logical topics into functions.

Component options could become complicated to be organized and hard to maintain (monster component). A logical topic could involve properties in props and data(), some methods, a certain hook (beforeMount/ mounted), and a watcher in watch. Hence one single topic will be fragmented across multiple options.

With Composition API, every function, which is a part of the big component, encapsulates all the code related to the logical topic (properties, methods, hooks, watchers). Now that smaller code (function) can be reused, and well-organized.

Use Vue 3 Composition API in current Vue 2 project

We can use new Vue 3 Composition API in our current Vue 2.x project by installing [@vue/composition-api](https://www.npmjs.com/package/@vue/composition-api) module.

It is so easy, just run the command:

npm install @vue/composition-api

Or

yarn add @vue/composition-api

Then import it in main.js.

import Vue from 'vue';
import CompositionApi from '@vue/composition-api';

Vue.use(CompositionApi);

Vue setup() function

[setup()](https://vue-composition-api-rfc.netlify.com/api.html#setup) is the new component option that we will use new Vue Composition API to setup the logic (logical topics) of the component. If setup() function becomes complex, we can easily split it into multiple functions with corresponding to logical topics.

When setup() is called?
It is called after props resolution, when an instance of the component is created.

Now look at the Vue component with setup() function:

const MyComponent = {
  props: {
    name: String
  },
  setup(props, context) {
    console.log(props.name);
    // context.attrs
    // context.slots
    // context.emit
    // context.parent
    // context.root
  }
}

The function has 2 arguments:
props
context

context has properties (attrs, slots, emit, parent, root) that are corresponding to this.$attrs, this.$slots, this.$emit, this.$parent, this.$root.

We can also destructure them with the latest values even after updates:

const MyComponent = {
  setup(props, { attrs }) {

    function onClick() {
      attrs.foo // automatically update latest value
    }
  }
}

*Note:this keyword is not available inside setup() function.

So this.$emit cannot be used like this:

setup() {
  function onClick() {
    this.$emit // not available
  }
}

this.$refs with new Composition API

To get a reference to an element or component instance in the template, we use [ref](https://vue-composition-api-rfc.netlify.com/api.html#ref) API so that setup() can return reactive and mutable object for render context.

import { ref } from '@vue/composition-api'

const MyComponent = {
  setup(props) {
    const name = ref('bezkoder.com')
    const appendName = () => {
      name.value = `hello ${props.name}`
    }
    return {
      name,
      appendName
    }
  },
  template: `<div @click="appendName">{{ name }}</div>`
}

ref automatically unwraps to the inner value, so we don’t need to append .value in the template: {{ name }} is enough, not {{ name.value }}.

Vue Composition API examples

In this section, we’re gonna show you examples that use new API along with old Vue2 options-based API syntax.

vue-function-api-example

Vue Composition API Computed Values

Vue2 options-based API syntax:

export default {
  props: {
    title: String
  },
  computed: {
    vTitle() {
      return '-' + this.title + '-';
    },
    itemsQuantity() {
      return this.items.length;
    }
  },
  data() {
    return {
      items: ['This', 'is'],
    };
  },
}

Vue 3 Composition API syntax:

import { ref, computed } from '@vue/composition-api';

export default {
  props: {
    title: String
  },
  setup(props) {
    const vTitle = computed(() => '-' + props.title + '-');

    const items = ref(['This', 'is']);
    const itemsQuantity = computed(() => items.value.length);

    return {
      vTitle,
      items,
      itemsQuantity,
    };
  }
};

With new computed API, we can create a writable ref object with get and set functions.

const count = ref(1)
const double = computed({
  get: () => count.value * 2,
  set: val => { count.value = val - 1 }
})

double.value = 3          // set: count.value = 3 - 1 = 2
console.log(count.value)  // 2
console.log(double.value) // get: count.value * 2 = 4

Vue Composition API Watchers

This is how we use Vue2 options-based API syntax:

export default {
  data() {
    return {
      items: ['This', 'is'],
      append: ''
    };
  },
  watch: {
    items: {
      handler: function(value, oldValue) {
        this.append = '';
        value.forEach(item => {
          this.append += item + ' ';
        });
      },
      immediate: true
    }
  },
}

Like watch option, we can use new Vue watch API to perform side effect everytime a state is changed.

The syntax is: watch(source, callback, options)

  • source: could be a getter function, a value wrapper, or an array containing the two above types (in case of watching multiple sources)
  • callback: is the function like Vue2 watcher handler function, with 2 arguments: newVal, oldVal. Each argument could be an array (for watching multiple sources): [newVal1, newVal2, ... newValN], [oldVal1, oldVal2, ... oldValN]
  • options (optional): is used for configuring watcher type containing: lazy, deep, flush.

For more details about WatchOption, please visit: api#watch.

import { ref, watch } from '@vue/composition-api';

export default {
  setup(props) { 
    const items = ref(['This', 'is']);
    const append = ref('');

    watch(
      // getter
      () => items.value,
      // callback
      (items, oldItems) => {
        append.value = '';
        items.forEach(item => {
          append.value += item + ' ';
        });
      },
      // watch Options
      {
        lazy: false // immediate: true
      }
    )

    return {
      items,
      append
    };
  }
};

In case we want to watch multiple sources:

watch([aRef, bRef], ([a, b], [prevA, prevB]) => {
  /* ... */
})

We can also split the multiple sources watcher into smaller watchers. This helps us organize our code and create watchers with distinct options:

watch(
  // getter
  () => items.value,
  // callback
  (items, oldItems) => {
    append.value = '';
    items.forEach(item => {
      append.value += item + ' ';
    });
  },
  // watch Options
  {
    lazy: false // immediate: true
  }
)

watch(
  // getter
  () => todo.value.length,
  // callback
  (length, oldLength) => {
    todoLength.value = length;
  },
  // watch Options
  {
    lazy: true // immediate: false
  }
)

Vue Composition API Lifecycle Hooks

With Vue2, we implement Lifecycle Hooks functions by this way:

export default {
  beforeMount() {
    console.log('V2 beforeMount!')
  },
  mounted() {
    console.log('V2 mounted!')
  }
};

New Vue 3 Composition API has equivalent functions, we can use those with on prefix inside setup() function:

import { onBeforeMount, onMounted } from '@vue/composition-api';

export default {
  setup() {
    onBeforeMount(() => {
      console.log('V3 beforeMount!');
    })

    onMounted(() => {
      console.log('V3 mounted!');
    })
  }
};

You can see the mapping between Lifecycle Vue2 Options and Composition API in the following table:

Vue 3 Composition API

Encapsulate logical Topics into Functions

Now we combine all code above into one Vue Component, you can see a complex component with multiple topics. We need to implement logic for title, for todo, for items:

import { ref, reactive, computed, watch, onBeforeMount, onMounted } from '@vue/composition-api';

export default {
  props: {
    title: String,
    initInput: String
  },
  setup(props) {
    const vTitle = computed(() => '-' + props.title + '-');

    const todo = ref(props.initInput);
    const todoLength = ref(0);

    const items = ref(['This', 'is']);
    const itemsQuantity = computed(() => items.value.length);
    const append = ref('');

    watch(
      // getter
      () => items.value,
      // callback
      (items, oldItems) => {
        append.value = '';
        items.forEach(item => {
          append.value += item + ' ';
        });
      },
      // watch Options
      {
        lazy: false // immediate: true
      }
    )

    watch(
      // getter
      () => todo.value.length,
      // callback
      (length, oldLength) => {
        todoLength.value = length;
      },
      // watch Options
      {
        lazy: false // immediate: true
      }
    )

    const add = () => {
      if (todo.value) {
        items.value.push(todo.value);
        todo.value = '';
      }
    };

    const remove = index => {
      items.value.splice(index, 1);
    };

    onBeforeMount(() => {
      console.log('V3 beforeMount!');
    })

    onMounted(() => {
      console.log('V3 mounted!');
    })

    return {
      vTitle,
      todo,
      todoLength,
      items,
      itemsQuantity,
      append,
      add,
      remove
    };
  }
};

It comes time to take advantage of Vue Composition API: split complex component into multiple functions with corresponding to logical topics:

import { ref, computed, watch, onBeforeMount, onMounted } from "@vue/composition-api";

function useTitle(props) {
  const vTitle = computed(() => "-" + props.title + "-");

  return {
    vTitle
  };
}

function useTodoLength(todo) {
  const todoLength = ref(0);

  watch(
    // getter
    () => todo.value.length,
    // callback
    (length, oldLength) => {
      todoLength.value = length;
    },
    // watch Options
    {
      lazy: false // immediate: true
    }
  );

  return {
    todoLength
  };
}

function useItems(todo) {
  const items = ref(["This", "is"]);
  const itemsQuantity = computed(() => items.value.length);
  const append = ref("");

  watch(
    // getter
    () => items.value,
    // callback
    (items, oldItems) => {
      append.value = "";
      items.forEach(item => {
        append.value += item + " ";
      });
    },
    // watch Options
    {
      lazy: false // immediate: true
    }
  );

  const add = () => {
    if (todo.value) {
      items.value.push(todo.value);
      todo.value = "";
    }
  };

  const remove = index => {
    items.value.splice(index, 1);
  };

  return {
    items,
    itemsQuantity,
    append,
    add,
    remove
  };
}

export default {
  props: {
    title: String,
    initInput: String
  },
  setup(props) {
    const todo = ref(props.initInput);

    onBeforeMount(() => {
      console.log("V3 beforeMount!");
    });

    onMounted(() => {
      console.log("V3 mounted!");
    });

    return {
      todo,
      ...useTitle(props),
      ...useTodoLength(todo),
      ...useItems(todo)
    };
  }
};

The results:

vue-function-api-example

It works like a charm.
We can easily view each topic by its own function. Each topic has its own props, data, watchers, methods. Our component now only need to inject these functions and return them inside its setup() function.

Fantastic!

Conclusion

Maybe you feel comfortable when using the old Vue options-based API, or maybe you don’t like to think of everything as functions but properties/methods with OOP mindset. The creators are developing Vue, make it better year after year and give us more options. Just try it and feel the good.

Happy learning! See you again!

Source Code

You can find the complete source code for this ‘Vue Composition Api example’ on Github.

#vue-js #vuejs #vue #javascript #web-development

What is GEEK

Buddha Community

A Beginner’s Guide to Vue 3 Composition API with Examples

Vue 3 Infinite Scroll with the Composition API

At the time of writing, Vue.js version 3 is in beta. However, that doesn’t mean we can’t start using it. In fact, this the best time to start experimenting with the new API and get ready for the official release.

In this tutorial, we will be building an infinite scroll hook with the new Composition API. we will be creating reactive-data, computed values, and using lifecycle methods.

#vue #composition-api #vue 3 #api

Sival Alethea

Sival Alethea

1624302000

APIs for Beginners - How to use an API (Full Course / Tutorial)

What is an API? Learn all about APIs (Application Programming Interfaces) in this full tutorial for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you’ll have no problem following along.
⭐️ Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:03:57)
⌨️ Video 3 - Defining API (0:07:51)
⌨️ Video 4 - Remote APIs (0:12:55)
⌨️ Video 5 - How the web works (0:17:04)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:22:00)

⭐️ Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:27:36)
⌨️ Video 2 - Using an API from the command line (0:44:30)
⌨️ Video 3 - Using Postman to explore APIs (0:53:56)
⌨️ Video 4 - Please please Mr. Postman (1:03:33)
⌨️ Video 5 - Using Helper Libraries (JavaScript) (1:14:41)
⌨️ Video 6 - Using Helper Libraries (Python) (1:24:40)

⭐️ Unit 3 - Using APIs
⌨️ Video 1 - Introducing the project (1:34:18)
⌨️ Video 2 - Flask app (1:36:07)
⌨️ Video 3 - Dealing with API Limits (1:50:00)
⌨️ Video 4 - JavaScript Single Page Application (1:54:27)
⌨️ Video 5 - Moar JavaScript and Recap (2:07:53)
⌨️ Video 6 - Review (2:18:03)
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=GZvSYJDk-us&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=5
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#apis #apis for beginners #how to use an api #apis for beginners - how to use an api #application programming interfaces #learn all about apis

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Luna  Mosciski

Luna Mosciski

1600583123

8 Popular Websites That Use The Vue.JS Framework

In this article, we are going to list out the most popular websites using Vue JS as their frontend framework.

Vue JS is one of those elite progressive JavaScript frameworks that has huge demand in the web development industry. Many popular websites are developed using Vue in their frontend development because of its imperative features.

This framework was created by Evan You and still it is maintained by his private team members. Vue is of course an open-source framework which is based on MVVM concept (Model-view view-Model) and used extensively in building sublime user-interfaces and also considered a prime choice for developing single-page heavy applications.

Released in February 2014, Vue JS has gained 64,828 stars on Github, making it very popular in recent times.

Evan used Angular JS on many operations while working for Google and integrated many features in Vue to cover the flaws of Angular.

“I figured, what if I could just extract the part that I really liked about Angular and build something really lightweight." - Evan You

#vuejs #vue #vue-with-laravel #vue-top-story #vue-3 #build-vue-frontend #vue-in-laravel #vue.js