tsyama記

プログラミングとそのほか

Vueとその中のthisについて

はじめに

こんなことをつぶやいた。

どういうこと

こういうコンポーネントがあるとして、

<template>
    <button type="button" v-on:click="shika(this.comment)">{{ this.comment }}</button>
</template>

<script>
    export default {
        name: "SampleButtonComponent",
        data: function () {
            return {
                comment: "これこれ"
            }
        },
        methods: {
            shika: function (kore) {
                this.comment = kore + "しかじか";
            }
        }
    }
</script>

<style scoped>

</style>

この中で、Vueインスタンスのdataであるthis.comment

  • template内:{{}}内部
  • template内:v-on属性
  • method内

の3箇所で使われていますが、2つ目のv-on属性ではthis.commentが取れずエラーになります。

正しくは、

v-on:click="comment"

のようにすると、Vueインスタンスthis.commentが取れてきます。
ちゃんと調べたわけではないですが、v-on属性内のthisをconsole.logで調べるとnullが取れてきたので、v-onの内部は文字列として扱われ、Vueインスタンス内部の同名のプロパティを探してるとかじゃないですかね。

Vue慣れてる人には常識かもしれませんが、Vue初心者であるところの僕はこいつのせいで一日を無駄にしたので書き記しておきます。

ちなみに

methodsの書き方次第でthisが取れなかったりする罠もあるみたいです。

tadaken3.hatenablog.jp