7
6

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で背景をページ毎に動的に変えたい

Last updated at Posted at 2019-11-25

やる事

「画像を投稿して、投稿した画像にコメントを付けたい」
「コメントページは別ページ」
「別ページの背景を投稿画像にしたい。」
できるだけ頭を使わずにVue.js/Nuxt.jsでやっていきましょう。

方法

ページ内の要素をdivで包む


<template>
  <div>
    <!-- ここに中身。カニ味噌とか -->
  </div>
</template>

div要素のスタイルをバインド

バインド自体はsrcなどの属性に対して行うのとまったく同じ。


<template>
  <div v-bind:style="pageStyle">
    <!-- ここに中身。ウニとか -->
  </div>
</template>

スクリプトで背景要素を設定する。

連想配列にスタイルを書いていく。CSSのプロパティは通常ケバブケースだが、ここではキャメルケースで書くこと。
あと"url('ebikaniuni')"の中にURLを入れる部分に注意。落ち着いて書きましょう。
ちなみにTemplate部に直で書いてもOKだったりする。とても読みにくくなるけど...。


<script>
export default {
  data() {
    return {
      pageStyle: {
        // 背景変更用スタイル
        backgroundImage: "", // 背景読み込み前なので空白
        backgroundRepeat: "no-repeat",
        backgroundAttachment: "fixed",
        backgroundPosition: "center center",
      }
    };
 },
  created() {
    this.pageStyle.backgroundImage = "url('" + gazouNoUrl + "')"; 
    // クォートをいい感じにエスケープする必要がある点に注意。
  },
}

</script>

もっといい方法があったら教えてクレメンス

参考資料

思考の葉:v-bindでstyle、classの属性値を変える[Vue.js]

7
6
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?