0
0

More than 1 year has passed since last update.

vue.jsのv-bindによるStyleの変更に関して

Posted at

V-bindによるStyle属性の変更に関して

最近vue.jsをキャッチアップする機会を頂いたので、youtubeを参考に寿司打をvue3で作っていた際に気づいたことを書きます。

※めっちゃ当たり前の内容かもしれませんが、自分が学習していく中で直面した問題のメモとして残します。

v-bindによるStyleのバインドの仕方

全問題数をquestionCountsとして分母
現在の問題数をcurrentQuestionCountsとして分子
currentQuestionCounts / questionCounts
として表示し、その問題が進むにつれてゲージが増えるという実装をしようと思っていました。

■最初に書いていた<template>内はこんな感じ

<template>
    <div :style="{ 'width': styleObject, 'backgroundColor': styleObject }"></div>
</template>

♦間違っている箇所

  • styleObject内のプロパティにアクセスできていなかった
    →styleObject.width, styleObject.backgroundColorと書き換えることで解決
    →そもそもstyleObjectは変数なので、:style="styleObject"と書いてしまえばいい

■最初に書いていた<script>内はこんな感じ

//
<script setup>
    const styleObject = computed( () => {
        const styleWidth = 20 * currentQuestionCounts.value + "%";
        const styleColor = () => {
            if(currentQuestionCounts.value == questionCounts.value) {
                color: "skyblue"
            }else{
                color: "orange"
            }
        return {
            "width": styleWidth,
            "backgroundColor": styleColor
        }
    });
</script>

♦間違っている箇所

  • styleColorで条件によって色指定をしたいだけなのに、アロー関数を使っているから戻り値がうまくStyleObjectに戻ってなかった
    →このままではStyleObjectに関数が入ってしまっているため、簡単に書き換える必要がある。

■修正後の<template>内はこんな感じ

<template>
    <div :style="styleObject"></div>
</template>

■修正後の<script>内はこんな感じ

<script setup>
    const styleObject = (computed () => {
        const styleWidth = 20 * currentQuestionCounts.value + "%";
        //もしくは
        const styleWidth = `${ 20 * currentQuestionCounts.value}`%;

        const styleColor = currentQuestionCounts.value === questionCounts.value ? "skyblue" : "orange";
        return {
            "width": styleWidth,
            "backgroundColor": styleColor
        }
    });
</script>

まとめ

今回のエラー修正で4時間近く悩んだ末にChatGPTに聞いたら5分で解決したという無駄なことをしてしまったので、戒めの為にも残すことにしました。
何か困ったらchatGPTに助けてもらうのが一番早いかも。。

とはいえ、こういう書き方は実際にやってみてエラーに直面して解決したときに一番覚えられるのでとてもいい経験になったと思いました。

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