Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

vuejs
javascript
communitycreator
options api

How to use the Options API in Vue 2

Educative Team

Options API

We use Options APIApplication Programming Interface in a Vue application to write and define different components. With this API, we can use options such as 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.

Syntax of 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 our data(), methods(), mounted(), etc. inside export default. Inside the <script> tags, we have our method clickCount(), which counts the total number of clicks. We also have the clearAll() function that resets the count to 0.

  • Line 27: We add CSSCascading Style Sheet for our program inside the <style> tags using @import.

RELATED TAGS

vuejs
javascript
communitycreator
options api
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring