Created
December 1, 2020 20:16
-
-
Save mcanv/8ae3bcad6e168b462abac10737eabdf8 to your computer and use it in GitHub Desktop.
Alpinejs - Get data from api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>AlpineJS - Get data from api</title> | |
| </head> | |
| <body> | |
| <h1>AlpineJS - Get data from api</h1> | |
| <div x-data="app()" x-init="init()"> | |
| <template x-for="(post, key) in posts.slice(0,visible)" :key="key"> | |
| <div> | |
| <h3 x-text="post.title"></h3> | |
| <p x-text="post.body"></p> | |
| </div> | |
| </template> | |
| <button x-show="posts.length !== 0 && visible < posts.length " @click="visible = visible + 3">Load more</button> | |
| </div> | |
| <script> | |
| function app() { | |
| return { | |
| visible: 3, | |
| posts: [], | |
| apiUrl: 'https://jsonplaceholder.typicode.com', | |
| init() { | |
| fetch(this.apiUrl+'/posts') | |
| .then(response => response.json()) | |
| .then(response => { | |
| if(response.length > 0) { | |
| this.posts = response; | |
| } else { | |
| console.log("Couldn't find any post") | |
| } | |
| }) | |
| }, | |
| } | |
| } | |
| </script> | |
| <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment