diff --git a/src/api/global-api.md b/src/api/global-api.md index 3a056c4e..c804ba4b 100644 --- a/src/api/global-api.md +++ b/src/api/global-api.md @@ -1,21 +1,39 @@ +--- +sidebarDepth: 1 +--- + # グローバル API +CDN ビルドを使っている場合、グローバル API の関数はグローバルな `Vue` オブジェクトを介してアクセスできます。例えば: + +```js +const { createApp, h, nextTick } = Vue +``` + +ES モジュールを使っている場合、それらは直接インポートできます: + +```js +import { createApp, h, nextTick } from 'vue' +``` + +`reactive` や `ref` など、リアクティビティを扱うグローバル関数は、別途ドキュメントがあります。それらの関数は [リアクティビティ API](/api/reactivity-api.html) を参照してください。 + ## createApp -Returns an application instance which provides an application context. The entire component tree mounted by the application instance share the same context. +アプリケーションのコンテキストを提供するアプリケーションインスタンスを返します。このアプリケーションインスタンスがマウントしているコンポーネントツリー全体は、同じコンテキストを共有します。 ```js -const app = Vue.createApp({}) +const app = createApp({}) ``` -You can chain other methods after `createApp`, they can be found in [Application API](./application-api.html) +`createApp` の後に他のメソッドをチェインできます。それらは [アプリケーション API](./application-api.html) に記載されています。 -### Arguments +### 引数 -The function receives a root component options object as a first parameter: +この関数は最初のパラメータとしてルートコンポーネントのオプションオブジェクトを受け取ります: ```js -const app = Vue.createApp({ +const app = createApp({ data() { return { ... @@ -27,10 +45,10 @@ const app = Vue.createApp({ }) ``` -With the second parameter, we can pass root props to the application: +2 番目のパラメータでは、そのアプリケーションのルートプロパティを渡せます: ```js -const app = Vue.createApp( +const app = createApp( { props: ['username'] }, @@ -45,7 +63,7 @@ const app = Vue.createApp( ``` -### Typing +### 型定義 ```ts interface Data { @@ -60,41 +78,41 @@ export type CreateAppFunction = ( ## h -Returns a returns "virtual node", usually abbreviated to **VNode**: a plain object which contains information describing to Vue what kind of node it should render on the page, including descriptions of any child nodes. It is intended for manually written [render functions](../guide/render-function.md): +一般的に **VNode** と略される「仮想ノード」を返します: これは Vue がページ上でレンダリングするノードの種類を記述した情報を含むプレーンオブジェクトで、子ノードの記述も含まれています。これは手動で書かれた [Render 関数](../guide/render-function.md) のためのものです: ```js render() { - return Vue.h('h1', {}, 'Some title') + return h('h1', {}, 'Some title') } ``` -### Arguments +### 引数 -Accepts three arguments: `type`, `props` and `children` +3 つの引数を受け取ります: `type` と `props` と `children` #### type -- **Type:** `String | Object | Function` +- **型:** `String | Object | Function` -- **Details:** +- **詳細:** - An HTML tag name, a component or an async component. Using function returning null would render a comment. This parameter is required + HTML タグ名、コンポーネント、非同期コンポーネント、または関数型コンポーネント。 null を返す関数を使うと、コメントがレンダリングされます。このパラメータは必須です。 #### props -- **Type:** `Object` +- **型:** `Object` -- **Details:** +- **詳細:** - An object corresponding to the attributes, props and events we would use in a template. Optional + テンプレートで使う属性、プロパティ、イベントに対応するオブジェクトです。省略可能です。 #### children -- **Type:** `String | Array | Object` +- **型:** `String | Array | Object` -- **Details:** +- **詳細:** - Children VNodes, built using `h()`, or using strings to get "text VNodes" or an object with slots. Optional + `h()` を使って構築された子供の VNode、または文字列をつかった「テキスト VNode」、もしくはスロットを持つオブジェクトです。省略可能です。 ```js h('div', {}, [ @@ -108,11 +126,11 @@ Accepts three arguments: `type`, `props` and `children` ## defineComponent -Implementation-wise `defineComponent` does nothing but return the object passed to it. However, in terms of typing, the returned value has a synthetic type of a constructor for manual render function, TSX and IDE tooling support. +実装的には `defineComponent` なにもせず、渡されたオブジェクトを返します。しかし型付けの面において、返り値は手動の Render 関数、TSX、IDE ツールがサポートするためのコンストラクタの合成型を持っています。 -### Arguments +### 引数 -An object with component options +コンポーネントのオプションを持つオブジェクトです。 ```js import { defineComponent } from 'vue' @@ -129,7 +147,7 @@ const MyComponent = defineComponent({ }) ``` -Or a `setup` function, function name will be used as component name +または `setup` 関数、関数名はコンポーネント名として使われます。 ```js import { defineComponent, ref } from 'vue' @@ -142,11 +160,11 @@ const HelloWorld = defineComponent(function HelloWorld() { ## defineAsyncComponent -Creates an async component that will be loaded only when it's necessary. +必要なときにだけ読み込まれる非同期コンポーネントを作成します。 -### Arguments +### 引数 -For basic usage, `defineAsyncComponent` can accept a factory function returning a `Promise`. Promise's `resolve` callback should be called when you have retrieved your component definition from the server. You can also call `reject(reason)` to indicate the load has failed. +基本的な使い方として、 `defineAsyncComponent` は `Promise` を返すファクトリ関数を受け取れます。 Promise の `resolve` コールバックは、サーバからコンポーネントの定義を取得したときに呼び出される必要があります。また、読み込みに失敗したことを示すために `reject(reason)` を呼び出すこともできます。 ```js import { defineAsyncComponent } from 'vue' @@ -158,7 +176,7 @@ const AsyncComp = defineAsyncComponent(() => app.component('async-component', AsyncComp) ``` -When using [local registration](../guide/component-registration.html#local-registration), you can also directly provide a function that returns a `Promise`: +[ローカル登録](../guide/component-registration.html#ローカル登録) を使っている場合は、`Promise` を返す関数を直接指定できます: ```js import { createApp, defineAsyncComponent } from 'vue' @@ -173,48 +191,61 @@ createApp({ }) ``` -For advanced usage, `defineAsyncComponent` can accept an object: +上級者向けには、 `defineAsyncComponent` にオブジェクトを受け取ることもできます: -The `defineAsyncComponent` method can also return an object of the following format: +`defineAsyncComponent` メソッドは、次のような形式のオブジェクトを返すこともできます: ```js import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent({ - // The factory function + // ファクトリ関数 loader: () => import('./Foo.vue') - // A component to use while the async component is loading + // 非同期コンポーネントが読み込み中に使うコンポーネント loadingComponent: LoadingComponent, - // A component to use if the load fails + // 読み込みが失敗したときに使うコンポーネント errorComponent: ErrorComponent, - // Delay before showing the loading component. Default: 200ms. + // 読み込み中のコンポーネントを表示するまでの時間。デフォルト: 200ms. delay: 200, - // The error component will be displayed if a timeout is - // provided and exceeded. Default: Infinity. + // タイムアウトが指定されていて、それを超えた場合、 + // エラーコンポーネントが表示されます。デフォルト: Infinity. timeout: 3000, - // A function that returns a boolean indicating whether the async component should retry when the loader promise rejects - retryWhen: error => error.code !== 404, - // Maximum allowed retries number - maxRetries: 3, - // Defining if component is suspensible - suspensible: false + // コンポーネントがサスペンド可能かの定義。デフォルト: true. + suspensible: false, + /** + * + * @param {*} error エラーメッセージのオブジェクト + * @param {*} retry 読み込みを待つ Promise がリジェクトされたときに、非同期コンポーネントが再試行するかを示す関数 + * @param {*} fail 失敗時の後処理 + * @param {*} attempts 再試行する最大数 + */ + onError(error, retry, fail, attempts) { + if (error.message.match(/fetch/) && attempts <= 3) { + // fetch のエラーを 3 回まで再試行 + retry() + } else { + // retry と fail は Promise の resolve と reject のようなものです: + // エラー処理を継続するために、これらのうち 1 つが呼び出される必要があります。 + fail() + } + }, }) ``` -**See also**: [Dynamic and Async components](../guide/component-dynamic-async.html) +**参照**: [動的 & 非同期コンポーネント](../guide/component-dynamic-async.html) ## resolveComponent :::warning -`resolveComponent` can only be used within `render` or `setup` functions. +`resolveComponent` は `render` または `setup` 関数内でのみ使えます。 ::: -Allows resolving a `component` by its name, if it is available in the current application instance. +現在のアプリケーションインスタンスで `component` が利用可能ならば、その名前で解決できます。 -Returns a `Component` or `undefined` when not found. +`Component` か、見つからなければ引数の `name` を返します。 ```js -const app = Vue.createApp({}) +const app = createApp({}) app.component('MyComponent', { /* ... */ }) @@ -227,27 +258,27 @@ render() { } ``` -### Arguments +### 引数 -Accepts one argument: `component` +1 つの引数を受け取ります: `name` -#### component +#### name -- **Type:** `String` +- **型:** `String` -- **Details:** +- **詳細:** - The name of a loaded component. + 読み込まれたコンポーネント名です。 ## resolveDynamicComponent :::warning -`resolveDynamicComponent` can only be used within `render` or `setup` functions. +`resolveDynamicComponent` は `render` または `setup` 関数内でのみ使えます。 ::: -Allows resolving a `component` by the same mechanism that `` employs. +`` が採用しているのと同じ方法で `component` を解決できます。 -Returns the resolved `Component` or a newly created `VNode` with the component name as the node tag. Will raise a warning if the `Component` was not found. +解決した `Component` か、コンポーネント名をノードタグに持つ新しく作成された `VNode` を返します。 `Component` が見つからなければ、警告を出します。 ```js import { resolveDynamicComponent } from 'vue' @@ -256,30 +287,30 @@ render () { } ``` -### Arguments +### 引数 -Accepts one argument: `component` +1 つの引数を受け取ります: `component` #### component -- **Type:** `String | Object (component’s options object)` +- **型:** `String | Object (コンポーネントのオプションオブジェクト)` -- **Details:** +- **詳細:** - For more details, refer to the documentation on [Dynamic Components](../guide/component-dynamic-async.html). + 詳しくは [動的コンポーネント](../guide/component-dynamic-async.html) のドキュメントを参照してください。 ## resolveDirective :::warning -`resolveDirective` can only be used within `render` or `setup` functions. +`resolveDirective` は `render` または `setup` 関数内でのみ使えます。 ::: -Allows resolving a `directive` by its name, if it is available in the current application instance. +現在のアプリケーションインスタンスで `directive` が利用可能ならば、その名前で解決できます。 -Returns a `Directive` or `undefined` when not found. +`Directive` か、見つからなければ `undefined` を返します。 ```js -const app = Vue.createApp({}) +const app = createApp({}) app.directive('highlight', {}) ``` @@ -290,25 +321,25 @@ render () { } ``` -### Arguments +### 引数 -Accepts one argument: `name` +1 つの引数を受け取ります: `name` #### name -- **Type:** `String` +- **型:** `String` -- **Details:** +- **詳細:** - The name of a loaded directive. + 読み込まれたディレクティブ名です。 ## withDirectives :::warning -`withDirectives` can only be used within `render` or `setup` functions. +`withDirectives` は `render` または `setup` 関数内でのみ使えます。 ::: -Allows applying directives to a **VNode**. Returns a VNode with the applied directives. +ディレクティブを **VNode** に適用できます。ディレクティブを適用した VNode を返します。 ```js import { withDirectives, resolveDirective } from 'vue' @@ -321,43 +352,43 @@ return withDirectives(h('div'), [ ]) ``` -### Arguments +### 引数 -Accepts two arguments: `vnode` and `directives`. +2 つの引数を受け取ります: `vnode` と `directives` #### vnode -- **Type:** `vnode` +- **型:** `vnode` -- **Details:** +- **詳細:** - A virtual node, usually created with `h()`. + 通常 `h()` で作成される仮想ノードです。 #### directives -- **Type:** `Array` +- **型:** `Array` -- **Details:** +- **詳細:** - An array of directives. + ディレクティブの配列です。 - Each directive itself is an array, which allows for up to 4 indexes to be defined as seen in the following examples. + 各ディレクティブ自身が配列で、次の例のように 4 つまでの要素を定義できます。 - - `[directive]` - The directive by itself. Required. + - `[directive]` - ディレクティブ自身。必須。 ```js const MyDirective = resolveDirective('MyDirective') const nodeWithDirectives = withDirectives(h('div'), [[MyDirective]]) ``` - - `[directive, value]` - The above, plus a value of type `any` to be assigned to the directive + - `[directive, value]` - 上記に加えて、ディレクティブに割り当てる `any` 型の値。 ```js const MyDirective = resolveDirective('MyDirective') const nodeWithDirectives = withDirectives(h('div'), [[MyDirective, 100]]) ``` - - `[directive, value, arg]` - The above, plus a `String` argument, ie. `click` in `v-on:click` + - `[directive, value, arg]` - 上記に加えて、`String` の引数、例えば `v-on:click` の `click`。 ```js const MyDirective = resolveDirective('MyDirective') @@ -366,7 +397,7 @@ Accepts two arguments: `vnode` and `directives`. ]) ``` - - `[directive, value, arg, modifiers]` - The above, plus a `key: value` pair `Object` defining any modifiers. + - `[directive, value, arg, modifiers]` - 上記に加えて、任意の修飾子を定義する `key: value` のペア `Object`。 ```js const MyDirective = resolveDirective('MyDirective') @@ -377,16 +408,16 @@ Accepts two arguments: `vnode` and `directives`. ## createRenderer -The createRenderer function accepts two generic arguments: -`HostNode` and `HostElement`, corresponding to Node and Element types in the -host environment. +createRenderer 関数は 2 つの一般的な引数を受け取ります: +ホスト環境のノードと要素の型に一致する +`HostNode` と `HostElement` です。 -For example, for runtime-dom, HostNode would be the DOM -`Node` interface and HostElement would be the DOM `Element` interface. +例えば runtime-dom の場合、 HostNode は DOM の `Node` インターフェイスに、 +HostElement は DOM の `Element` インターフェイスになります。 -Custom renderers can pass in the platform specific types like this: +カスタムレンダラは、このようにプラットフォーム固有の型を渡せます: -```js +```ts import { createRenderer } from 'vue' const { render, createApp } = createRenderer({ patchProp, @@ -394,29 +425,29 @@ const { render, createApp } = createRenderer({ }) ``` -### Arguments +### 引数 -Accepts two arguments: `HostNode` and `HostElement` +2 つの引数を受け取ります: `HostNode` と `HostElement` #### HostNode -- **Type:** `Node` +- **型:** `Node` -- **Details:** +- **詳細:** - The node in the host environment. + ホスト環境のノードです。 #### HostElement -- **Type:** `Element` +- **型:** `Element` -- **Details:** +- **詳細:** - The element in the host environment. + ホスト環境の要素です。 ## nextTick -Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update. +次の DOM 更新サイクルの後に実行するようにコールバックを遅延します。いくつかのデータを変更した直後に使って、DOM の更新を待ちます。 ```js import { createApp, nextTick } from 'vue' @@ -433,4 +464,89 @@ const app = createApp({ }) ``` -**See also**: [`$nextTick` instance method](instance-methods.html#nexttick) +**参照**: [`$nextTick` インスタンスメソッド](instance-methods.html#nexttick) + +## mergeProps + +VNode のプロパティを含む複数のオブジェクトを受け取り、それらを単一のオブジェクトにマージします。新しく作られたオブジェクトが返され、引数として渡されたオブジェクトは変更されません。 + +いくつでもオブジェクトを渡すことができますが、後ろの引数のプロパティが優先されます。イベントリスナは `class` や `style` と同じくらい特別に扱われ、これらのプロパティの値は上書きではなくマージされます。 + +```js +import { h, mergeProps } from 'vue' + +export default { + inheritAttrs: false, + + render() { + const props = mergeProps({ + // class は $attrs の class とマージされます + class: 'active' + }, this.$attrs) + + return h('div', props) + } +} +``` + +## useCssModule + +:::warning +`useCssModule` は `render` または `setup` 関数内でのみ使えます。 +::: + +[単一ファイルコンポーネント](/guide/single-file-component.html) の [`setup`](/api/composition-api.html#setup) 関数内で、CSS モジュールにアクセスできるようになります: + +```vue + + + +``` + +CSS モジュールの使い方について詳しくは、 [Vue Loader - CSS Modules](https://vue-loader.vuejs.org/guide/css-modules.html) を参照してください。 + +### 引数 + +1 つの引数を受け取ります: `name` + +#### name + +- **型:** `String` + +- **詳細:** + + CSS モジュール名。デフォルトは `'$style'`。 + +## version + +インストールされている Vue のバージョンを文字列で提供します。 + +```js +const version = Number(Vue.version.split('.')[0]) + +if (version === 3) { + // Vue 3 +} else if (version === 2) { + // Vue 2 +} else { + // Unsupported versions of Vue +} +``` + +**参照**: [Application API - version](/api/application-api.html#version)