0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

vue.js コンポーネントを作成する

0
Posted at

コンポーネントは再利用可能なvueインスタンス。
何度も使うコードをコンポーネント化して再利用が簡単にできる。
受け取ったデータを処理して返すなどの処理もできるが、今回は文字を登録しておくだけ。

コンポーネントファイルの作成

child.vue などの名前でコンポーネントファイルを作成する。
複数作っていくことになるのでプロジェクト内の/componentsフォルダに保存しよう。

child.vue
<template>
    <p>text here</p>
</template>

コンポーネントの呼び出し

呼び出し元は"親コンポーネント"、呼び出される側は"子コンポーネント"と呼ばれる。

親側でまずはどんなコンポーネントがあるのか登録する必要がある。
コンポーネント登録の方法はグローバルとローカルの2種類。

グローバル登録

main.jsに書きの記述で登録する。
importで外部ファイル(Child.vue)を読み込み、
Vue.component()で登録される。

main.js
import Child from './components/Child.vue'
Vue.component('Child', Child);

ローカル登録

親となるコンポーネントファイルの<script>タグ内で登録する。
こちらでもimportで読み込み。
export default {}のコンポーネントプロパティに登録する。

parent.vue
<script>
import Child from "./components/Child"
export default{
  components: {
    Child
  },
};
</script>

呼び出し

親コンポーネント側で、HTMLタグと同様の記述で呼び出し、ページに表示される。

parent.vue
<template>
<div>
  <Child></Child>
</div>
</template>

コンポーネント間でのデータのやり取りはまた別の記事で。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?