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 3 years have passed since last update.

【Vue.js基礎】コンポーネントを作成してApp.vueを編集する

Posted at

やりたいこと

  • Vue.jsコンポーネントの基礎を学習する。
  • .vueファイルを編集して画面表示を確認する。

前提

Vue.jsの実行環境が構築済みであること。
まだの場合は環境構築手順
AlmaLinux8.3にvue-cli@2.9.6をインストールしてVue.jsを動かすまで
https://qiita.com/kenichiro-yamato/items/7f946e0215d4f08e4eca
を参照。

src/App.vue 編集

Vueプロジェクトを作成すると、下記のようなファイルやディレクトリが生成される。

image.png

HTML, CSS, JavaScriptの経験者でVue.jsが初めての人は、最初に

src/App.vue

を編集すると動作が理解しやすい。

エディタ等で上書きできない場合はパーミッションを確認する。

chmod 777 src
chmod 777 App.vue

たとえばApp.vueを下記のように修正する。

App.vue
<template>
    <div>
        <h1>{{ main_title }}</h1>
        <h2>{{ sub_title }}</h2>
    </div>
</template>

<script>
export default {
    data(){
        return {
            main_title: "ここにメインタイトルを記入する。あいうえお。",
            sub_title: "ここにサブタイトルを記入する。かきくけこ。"
        }
    }
}
</script>

<style scoped>
h1{color: red}
h2{color: blue}
</style>

image.png

日本語が文字化けする場合は、
.vueファイルの文字コードをutf8にする。

.vueファイルに、別の.vueファイルを読み込む

App.vue
と同じディレクトリに
Tokyo.vue
Osaka.vue
を作成し、その2ファイルを
App.vueで読み込んで表示する。

Tokyo.vue

Tokyo.vue
<template>
    <div>
        <h1>{{ main_title }}</h1>
        <h2>{{ sub_title }}</h2>
    </div>
</template>

<script>
export default {
    data(){
        return {
            main_title: "東京都",
            sub_title: "とうきょうと"
        }
    }
}
</script>

<style scoped>
h1{color: red}
h2{color: blue}
</style>

Osaka.vue

Osaka.vue
<template>
    <div>
        <h1>{{ main_title }}</h1>
        <h2>{{ sub_title }}</h2>
    </div>
</template>

<script>
export default {
    data(){
        return {
            main_title: "大阪府",
            sub_title: "おおさかふ"
        }
    }
}
</script>

<style scoped>
h1{color: orange}
h2{color: green}
</style>

App.vue

App.vue
<template>
  <div>
    <Tokyo></Tokyo>
    <Osaka></Osaka>
  </div>
</template>

<script>
import Tokyo from './Tokyo.vue'
import Osaka from './Osaka.vue'

export default {
  components: {
    Tokyo,
    Osaka
  }
}
</script>

ファイルは同じディレクトリに置いてある。

image.png

ブラウザでの表示は下記の通り。

image.png

componentsディレクトリ

src
ディレクトリの中に
components
というディレクトリがあらかじめ作成されており、
この中にTokyo.vueOsaka.vueファイルを置いてApp.vueにて

App.vue
import Tokyo from './components/Tokyo.vue'
import Osaka from './components/Osaka.vue'

のように読み込むことも可能。

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?