LoginSignup
6
2

More than 3 years have passed since last update.

Vuejs CLIにて一部を外部htmlファイルを読み込んで実装する方法

Posted at

Vuejs CLI環境下で一部をhtmlで実装したい時

Vuejs CLIでvue拡張子のファイル内で一部をhtmlファイルを読み込んで実装したい時がある方、
その方々に、試行錯誤を経て分かった方法を共有します。

参考

環境の整理

  • 開発環境:Vuejs CLIでインストールしたばかりの環境

方法

  1. Vuejs CLIをインストールする。
  2. HelloWorld.vueが生成される、その中を以下のように変更。

    HelloWorld.vue
    
    <template>
      <div class="hello">
        <p>Practice</p>
        <div v-html="htmlContent"></div>
      </div>
    </template>
    
    <script>
    export default {
      name: "HelloWorld",
      data() {
        return {
          htmlContent: "",
        };
      },
      mounted: function () {
        this.loadHtml();
      },
      methods: {
        loadHtml() {
          fetch("./html/sample.html").then((res) => {
            res.text().then((html) => {
              this.htmlContent = html;
            });
          });
        },
      },
    };
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    h3 {
      margin: 40px 0 0;
    }
    ul {
      list-style-type: none;
      padding: 0;
    }
    li {
      display: inline-block;
      margin: 0 10px;
    }
    a {
      color: #42b983;
    }
    </style>
    

    肝は
    *v-htmlを使用
    *dataにv-htmlで使用しているデータhtmlContentを紐づける
    *mountedにて、fetch使用のメソッドloadHtmlを読み込む
    *methodsにて、メソッドloadHtmlを定義し、fetchで外部htmlを読み込んで、
     htmlをデータhtmlContentに格納する。

  3. fetchメソッドに書いたパス(./html/sample.html)に
    sample.html(=今回対象となる一部htmlファイル)を格納する。
    *publicフォルダの中となる。
    1.png

  4. sample.html中は以下のようにstyle, htmlタグを書くことができる。

    sample.html
    <style>
      .text {
        color: red;
      }
    </style>
    
    <div class="text">Hello ! External.htmlだよ! </div>
    
  5. npm run serveコマンドを実行、ブラウザーで確認すると、以下が確認できる。
    2.png

npm run buildコマンドを実行しビルドした場合、
 distフォルダ内にhtmlはそのまま格納される。
 (このsample.htmlを直した場合もブラウザーに問題なく反映された。)
3.png

6
2
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
6
2