#VueCompositionAPI
Explore tagged Tumblr posts
katyslemon · 4 years ago
Text
How to Build To-do App using Vue Composition API and Vuex 4 with Typescript
Quick Summary:
Vue Composition API- Organized, Readable, and Understandable
Tumblr media
Introduction
In this tutorial, we will learn and explore Vue Composition API. You might have heard about it, but if not then don’t worry at all! We will start from the basics. For knowing Vue Composition API in a better way you must have knowledge about Options API, we will discuss that too!
I would suggest you visit my previous blog of the Vue 3 Tutorial series- How to Build To-do App with Vue 3 Typescript for setting up the basic demo project because in this tutorial we will be using the same github repository.
What is Vue Composition API?
Vue Composition API is function-based APIs that provides flexibility, improves code readability, and helps to maintain component logic. The main reason for introducing Vue Composition API was to address the limitations of Options API as the component gets larger.
Here are some of the limitations associated with Options API-
Ineffective patterns for reusing logic and component
Poor readability when component grows larger
Code gets complex and difficult to manage when the project size increases
Creates confusion and makes it difficult to use Typescript with ‘this.’
Vue Composition API vs Options API
You might have seen this image if you are learning Vue Composition API. Let’s see briefly what does it mean.
The difference in the component because of Vue Composition API
You will notice a setup() function is the major change. It comprises the component’s logic. In Options API we used to define data, methods, lifecycle, etc separately as a component option, but due to composition API, setup() function will consist of all these.
You might not understand the impact of this update until your component size grows larger. If you worked with a large project having complex component code or have to understand other developers’ code, you might understand the significance of code understandability and readability.
Vue Composition API sorts the component code and makes the logic reusable in a much better way.
Tumblr media
Let’s take a sample code from the Github repository: Vue 3 Typescript, which we have built in the previous blog- How to Build a To-do App with Typescript: Vue 3 Tutorial.
Read more: Vue Composition API vs Options API
0 notes
t-baba · 5 years ago
Photo
Tumblr media
Building a Shopping List App with the Vue Composition API
This article will show how the Vue Composition API is a great way to make your code more readable and maintainable. With the composition API introduced in Vue 3, handling of methods and component state is made more accessible.
The Composition API is a new and optional way of creating and organizing components in a Vue 3 application. It allows reactive component logic to be defined more intuitively by allowing all the code for a specific feature (search, for example) to be grouped. Using the Vue Composition API will make your application more scalable and reusable between several components.
In this article, we’ll build a simple shopping List app with the Vue Composition API.
You can check out a live demo of the app we’re building.
Prerequisites
For this tutorial, you’ll need:
a basic understanding of HTML, CSS, JavaScript, and Vue
a text editor
a web browser
Node.js
Vue CLI
Setting Up the Vue Application
Now let’s start by installing Vue Cli:
npm install -g vue-cli
This command will install Vue globally.
We’ll use the Vue CLI to build a simple application. To do that, open up your terminal and type the following:
vue create vueshoppinglist
After installation, move into the folder using the cd vueshoppinglist and run npm run serve.
This starts a development server that allows you to view your app on localhost:8080.
It’s now time to set up a nice Vue project.
The Vue Composition API
To Install the Composition API from the root of your project, run the following:
npm install --save @vue/composition-api
After successfully installing, we’ll import it into our project.
Modify src/main.vue to register the Composition API globally in our application, so that we can use it in all our application components:
import Vue from 'vue' import App from './App.vue' import VueCompositionApi from '@vue/composition-api' Vue.config.productionTip = false Vue.use(VueCompositionApi) new Vue({ render: h => h(App), }).$mount('#app')
Building Out the User Interface
We’ll need a component that will house the UI of our app. Create a new ShoppingList.vue component in the src/components/ directory and paste the following into the file:
<template> <section> <div class="form-container"> <h2>Add Item</h2> <form> <div> <label>Product name</label> <br /> <input type="text" /> </div> <div> <button type="submit" class="submit">Add Item</button> </div> </form> </div> <div class="list-container"> <ul> <li> Shopping List app <span style="float:right;padding-right:10px;"> <button>X</button> </span> </li> </ul> </div> </section> </template> <script> export default {}; </script> <style scoped> input { width: 20%; height: 30px; border: 2px solid green; } .submit { margin: 10px; padding: 10px; border-radius: 0px; border: 0px; background: green; color: white; } ul li { list-style: none; border: 2px solid green; width: 30%; margin-top: 10px; } </style>
The code snippet above is the initial boilerplate of our UI. We’ll now import our new component ShoppingList.vue to App.vue as shown below:
<template> <div id="app"> <img alt="Shoppingd List" src="./assets/shopping.png"> <shopping-list msg="Welcome to Your Vue.js App"/> </div> </template> <script> import ShoppingList from './components/ShoppingList.vue' export default { name: 'App', components: { ShoppingList } } </script> <style> #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; } </style>
Continue reading Building a Shopping List App with the Vue Composition API on SitePoint.
by Deven Rathore via SitePoint https://ift.tt/2F241lS
0 notes
tak4hir0 · 5 years ago
Link
Vue Composition API によって Vue.js にも React Hooks のようなロジックの再利用性の高い開発体験がもたらされようとしています。 しかし、まだ「Composition API の良さをわかっていない」という方や「Composition API をうまく利用した書き方がわからない」という方も多いかと思います。 本記事では Composition API 時代の便利ライブラリ VueUse を用いた実装例や、 VueUse 自体の実装がどのようなものか紹介します。 Composition API の良さや雰囲気もキャッチアップしていただければ幸いです。 VueUse とは? VueUse は Anthony Fu さん1が中心に開発しているライブラリで、Composition API を用いた便利系関数を数多く集めたライブラリです。 例えば、ブラウザ上のマウスポインタの座標をリアクティブに取得する useMouse(), ブラウザ API の localStorage を使って状態を保持できる useLocalStorage(), 負荷対策のために連続する関数呼び出しを防ぐ useDebounceFn() 2などといった関数が提供されています。 公式サイト: https://vueuse.js.org/ GitHub: antfu/vueuse npm: @vueuse/core 検証環境の構築 GitHub リポジトリの Description に記載通り、Vue 2系・3系のどちらでも利用可能です: 🧰 Collection of Composition API utils for Vue 2 and 3 https://vueuse.js.org/ 今回は Vue CLI で立ち上げた Vue 2.6 系のプロジェクトに @vue/composition-api をプラグインとして追加した環境で検証します。 動作確認した環境 macOS Catalina Node.js 12.18.1 npm 6.14.5 Vue CLI v4.4.4 Chrome 83 Vue CLI のインストール Vue CLI をグローバルインストールしたくない方は、以下の手順の vue コマンド部分を npx @vue/cli に読み替えていただいても大丈夫です。 プロジェクトの作成 vue-2-vueuse-trial というプロジェクト名で環境を構築していきます: vue create vue-2-vueuse-trial 設定は以下のようにしました: Vue CLI v4.4.4 ? Please pick a preset: Manually select features ? Check the features needed for your project: Babel, TS, Linter ? Use class-style component syntax? No ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? No ? Pick a linter / formatter config: Basic ? Pick additional lint features: Lint on save ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files ? Save this as a preset for future projects? No プラグインと VueUse の導入 プロジェクトディレクトリが出来上がったら、@vue/composition-api と VueUse を npm install します: cd vue-2-vueuse-trial npm i @vueuse/core@vue2 @vue/composition-api src/main.ts に Vue.use(VueCompositionApi) を追加します3: src/main.ts import Vue from 'vue' +import VueCompositionApi from '@vue/composition-api' import App from './App.vue' +Vue.use(VueCompositionApi) Vue.config.productionTip = false npm run serve で開発ビルドを開始してください。 VueUse の関数を使ってみる useMouse() リアクティブにマウスポインタの座標が取得できる useMouse() を使ってみます: src/App.vue <template {{ x }}, {{ y }} </template <script lang="ts" import { defineComponent } from '@vue/composition-api' import { useMouse } from '@vueuse/core' export default defineComponent({ setup() { // tracks mouse position const { x, y } = useMouse() return { x, y } } }) </script これだけでマウスポインタの座標がリアクティブに反映されていることがわかるかと思います。 useMouse() の実装を確認すると useEventListener() という関数を使っていて、 useEventListener() はコンポーネントのマウント時(Composition API の onMounted() を利用)にイベントリスナーを追加していることがわかります: https://github.com/antfu/vueuse/blob/master/packages/core/useMouse/index.ts https://github.com/antfu/vueuse/blob/master/packages/core/useEventListener/index.ts VueUse ではこのような関数がより抽象的な関数を参照しているパターンの実装が所々に見られます。 Composition API を用いた良い実装の例として知っておくと良いかと思います。 useLocalStorage() ブラウザ API の localStorage を使って状態を保持できる useLocalStorage() を使ってみます。 まずは useLocalStorage() を使わず、 VueUse がなくても利用できる reactive() 4 を使ってみましょう: src/App.vue <template name: <input v-model="state.name" color: <input v-model="state.color" {{ state }} </template <script lang="ts" import { defineComponent, reactive } from '@vue/composition-api' export default defineComponent({ setup() { const state = reactive({ name: 'Apple', color: 'red', }) return { state } } }) </script name, color を変更すると、下に表示されている JSON 形式の state の表示も更新される画面が表示されます: 上記の実装では name を Banana, color を yellow のように変更してページをリロードすると、元の状態(name が Apple, color が red)に戻ります。 以下のように ブロックを変更し、reactive() の代わりに useLocalStorage() を利用するように変更してみます: import { defineComponent } from '@vue/composition-api' import { useLocalStorage } from '@vueuse/core' export default defineComponent({ setup() { // persist state in localStorage const state = useLocalStorage( 'my-storage', { name: 'Apple', color: 'red', }, ) return { state } } }) state が localStorage に保存されるようになったので、ページをリロードしても状態が保持されるようになりました。 サンプルアプリとしてよくある ToDo リストの状態管理に useLocalStorage() を使うようにすると、手軽にデータを保存できる ToDo リストにできて楽しいかもしれません。 公式サイトが Storybook でできている件 公式サイトが Storybook でできてい���、各関数を即座に試せるリファレンスとなっています。 各関数のページ下部には関数の "Source" へのリンクがあり、ソースを見てどのような実装になっているか追っていくと Composition API を用いた良い実装の勉強となるかと思います。 所感 VueUse は多くの便利関数を提供しているので、今後お世話になる可能性が高いライブラリだと思いました。 まだ試せていない関数が多くあるので、使ってみたりコードを読んだりしてみようかと思います。
0 notes