Vue 3とTypescript入門入門


2022年3月、Vue 3 + TypesScriptで初の本格的プロジェクトを構築しました.そして、私はふざけていました-これらの2つは、一緒に遊びます.Vue 2とVue 3の間で開発者の経験に関する世界があるように感じた.
私が気づいた利点の中には
  • 優れたVSCodeコード補完
  • コンポーネントと構成機能の巧妙なインポートの提案
  • 便利なコード抽象化
  • このシリーズはあなたのためです.
  • あなたのVueアプリをより堅牢にするために
  • Vue 3が以前のバージョンと異なる方法について興味があります
  • あなたのVueアプリでTypeScriptを使用してください
  • 既にフック?グレート.ジャンプしましょう!

    VITEでアプリを設定する


    Viteは迅速なボイラメッキを可能にします.お好みのプロジェクトフォルダーのターミナルを開きます.次に、次のように入力します.
    yarn create vite
    
    # for NPM
    npm create vite@latest
    
  • フレームワークとしてVueを選択

  • プロジェクトのバリアントとしてVue tsを選択

    実行yarn & yarn dev 開発サーバーを起動するには

    プロジェクトのファイル構造


    次のボイラープレートを受け取ります.JavaScriptのボイラープレートとは異なる2つのファイルがあります.それらを見てみましょう.

    envD . TSファイル


    小さいサイズにもかかわらず、このファイルはpowerhouseです.グローバルマップDefineComponent すべてへの型.vue ファイル.つまり、すべてのVueコンポーネントのTypeScript IntelliSenseを意味します!
    /// <reference types="vite/client" />
    
    declare module '*.vue' {
      import type { DefineComponent } from 'vue'
      // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
      const component: DefineComponent<{}, {}, any>
      export default component
    }
    

    tsconfigJSONファイル


    TSコンパイラがプロジェクトと対話する方法の構成を保持します.ここで変更を加える必要はありません.チェックアウトthe official docs もっと学ぶ.
    {
      "compilerOptions": {
        "target": "esnext",
        "useDefineForClassFields": true,
        "module": "esnext",
        "moduleResolution": "node",
        "strict": true,
        "jsx": "preserve",
        "sourceMap": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "esModuleInterop": true,
        "lib": ["esnext", "dom"],
      },
      "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
      "references": [{ "path": "./tsconfig.node.json" }]
    }
    

    HelloWorldVueファイル


    BoilerPlateコンポーネントを見てみましょう.あなたがVue 3でまだ働いていないならばVue's Composition API . 詳細は別の記事で調べます.まず、3つの異なるコンポーネントのセットアップを比較することによって何が起こっているかを理解しようとしましょう.
  • 共通options 単一のデフォルトコンポーネントエクスポートによるAPIアプローチ
  • 共通composition セットアップ手法によるAPIアプローチ
  • 新しい人composition セットアップ属性のAPIアプローチ
  • タイプスクリプト+オプションAPI


    伝統的なVueアプリでは、単一のデフォルトのエクスポートを宣言します.これはコンポーネントです.それはあなたのHTMLテンプレートにデータとロジックを提供します.
    <script lang="ts">
    export default {
      data: () => ({
        count: 0,
      }),
      props: {
        msg: {
          type: String,
          required: true,
        },
      },
      methods: {
        increment() {
          this.count++;
        },
      }
    };
    </script>
    
    <template>
      <h1>{{ msg }}</h1>
    
      <button type="button" @click="increment">count is: {{ count }}</button>
      <p>
        Edit
        <code>components/HelloWorld.vue</code> to test hot module replacement.
      </p>
    </template>
    
    これは完全に有効なアプローチですが、コードの1000行を超える単一のUEファイルを試してみてください.それはすべての状態が単一のオブジェクト内で集計されます.メソッドまたは計算されたプロパティは、おそらく下に位置している可能性があります.前後の状態とロジック間のジャンプはすぐに退屈になります.

    HelloWorld -セットアップスクリプト+セットアップ方法


    セットアップメソッドを見ます.それは本質的にデータとロジックを分離することができ、Vueの組成APIへのゲートウェイです.
    これは、オプションAPIから重要な違いが付属しています:セットアップメソッドは、コンポーネントが作成される前に評価されます.その結果、内部setup , Vueインスタンスへのアクセスはありませんthis .

    Instead of using this.(...), you can access props and the component's context by two arguments of the setup function


    次のコードは、上記のオプションAPI APIに相当します.
  • 用途ref 変数を作成するcount 反応
  • セットアップを使用して提供するcount and increment テンプレートに
  • <script lang="ts">
    import { ref } from 'vue';
    
    export default {
      props: {
        msg: {
          type: String,
          required: true,
        },
      },
      setup(props, { attrs, emit, slots }) {
        const count = ref(0);
        const increment = () => count.value++;
        return { count, increment };
      },
    };
    </script>
    
    <template>
      <h1>{{ msg }}</h1>
    
      <button type="button" @click="increment">count is: {{ count }}</button>
      <p>
        Edit
        <code>components/HelloWorld.vue</code> to test hot module replacement.
      </p>
    </template>
    
    専用の代わりにdata and method セクションでは、セットアップメソッドの両方を宣言しました.

    セットアップ・シンタックス


    今まで、私たちは本当に多くのタイプスクリプトの使用をしませんでした.小道具もオブジェクト構文を使用して宣言されます.これを変える時間です.
    Vue 3のベータ期が終わる前に.this RFC 合成APIの組成APIを提供します.それも、私がとても強力であるとわかった現代のVue + Ts構文のために道を開きました.

    With <script setup>...</script>> There is no need to return any components, variables or functions to the template. They're simply available to the template.


    これがコードで何を意味するか見てみましょう.
    <script setup lang="ts">
    import { ref } from 'vue';
    
    defineProps<{ msg: string }>();
    
    const count = ref(0);
    const increment = () => count.value++;
    </script>
    
    <template>
      <h1>{{ msg }}</h1>
    
      <button type="button" @click="increment">count is: {{ count }}</button>
      <p>
        Edit
        <code>components/HelloWorld.vue</code> to test hot module replacement.
      </p>
    </template>
    
    それはタイプスクリプトのちょうど4行です!ボーナスとして、型は自動的に親コンポーネントに伝播されます.
    試してみて、msg 親コンポーネントのプロパティ.

    残りはどこですか。


    小道具、エックス、属性とスロットに何が起こったのですか?
  • 小道具と排出物を投入したcompiler macros , そのうちの一つはdefineProps
  • デフォルトのプロップはwithDefaults
  • 属性とスロットを別々にインポートする必要があります.
    それらはまだテンプレートで利用可能です$attrs & $slots
  • これらを詳細に別々の記事で説明します.あなたが簡単な概要の後、ここを見てください
    <script setup lang="ts">
    import { ref, withDefaults, useSlots, useAttrs } from 'vue';
    
    const props = withDefaults(
      defineProps<{
        msg: string;
      }>(),
      { msg: 'Hello World!' }
    );
    
    const emit = defineEmits<{
      (event: 'click', count: number): void;
    }>();
    
    const slots = useSlots();
    const attributes = useAttrs()
    
    const count = ref(0);
    const increment = () => count.value++;
    </script>
    
    <template>
      <h1>{{ msg }}</h1>
    
      <button type="button" @click="increment">count is: {{ count }}</button>
      <p>
        Edit
        <code>components/HelloWorld.vue</code> to test hot module replacement.
      </p>
    </template>
    

    ラッパ


    これまでのところ、
  • Vue 3を作成します
  • プロジェクト固有のファイルの概要
  • Vueのオプションと構成APIの違いをカバー
  • IntelliSenseが開発中にどのように我々を助けるかについて概説しました
  • フォローアップ記事では、さらに深くこれらのトピックに飛び込むとVueの最新バージョンは、私たちのためにその袖を持っているものを探る.