How to use the Options API in Vue 2
Options API
We use Options data, methods, and mounted.
To state it simply, Options API is an old way to structure a Vue.JS application. Due to some limitations in this API, Composition API was introduced in Vue 3.
Syntax
The illustration given below shows the structure of an Options API.
Code
Let’s implement Options API and see how it works.
Note: After executing, click on the “Add +1” button to increment the counter by 1. Press “Reset” to make it 0 again.
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
#p1 {
border: 1px solid black;
margin-right: 220px;
margin-left: 220px;
padding: 10px;
}
#btn1 {
padding: 10px;
margin-right: 10px;
color: green;
}
#btn2 {
padding: 10px;
margin-left: 10px;
color: red;
}Explanation
-
Lines 1–7: We have the
<template>tag. The<template>tag is where we define our HTML elements as written below (<p>,<button>, etc). -
Lines 9–25: We have our
<script>tag where the core JavaScript of our program is written. We write ourdata(),methods(),mounted(), etc. insideexport default. Inside the<script>tags, we have our methodclickCount(), which counts the total number of clicks. We also have theclearAll()function that resets the count to 0. -
Line 27: We add
for our program inside theCSS Cascading Style Sheet <style>tags using@import.
Free Resources