10
10

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.jsでは_(アンダースコア)から始まるプロパティの使い方には気をつけましょう

Posted at

結論

Vue の内部的なプロパティや API メソッドと衝突する可能性があるため、_ または $ から始まるプロパティは Vue インスタンスにプロキシされないことに注意してください。それらは vm.$data._property としてアクセスできます。

Vue.jsの公式サイトより(2018/11/2時点)

現象

動作検証のため、以下の様なコードを作成。
内容としては、「ボタンを押してから5秒間は、ボタンを押せない様にする」というものです。

<template>
	<div>
		<button @click="handleClick()" :disabled="isDisabled">クリック</button>
	</div>
</template>

<script lang="ts">
	import { Component, Vue } from "vue-property-decorator";

	@Component
	export default class Connpass extends Vue {
		private _running: boolean = false;

		get isDisabled(): boolean {
			return this._running;
		}

		sleep( msec: number ): Promise<any> {
			return new Promise(
				resolve => setTimeout( resolve, msec )
			);
		}

		async handleClick(): Promise<any> {
			if ( this._running === true ) {
				console.log( "すでに待機中ですよ?" );
				return;
			}
			this._running = true;

			console.log( "...待機中" );
			await this.sleep( 5000 );

			this._running = false;
		}
	}
</script>

これを実行したところ、無効にならない。
試しにconsole.log(this._running);を実行すると、出力はundefinedになる。

調べたところ、表題の記述に行き着いたわけです。

ちなみに、参照した記述にもある様に、this._runningthis.$data._runningとするといけます。
ただ、そうするくらいなら大人しく_(アンダースコア)は消そうと思いました。

接頭辞に_(アンダースコア)問題

Q. そもそも、なぜ先頭にアンダースコアを入れる様になったの?
A. (たぶん)当時のチームのコード規約で決めたから。

その後も使い続けているのは、なんとなくでしたが、改めて考えてみるとプライベートメンバ変数だとパッと見でわかりやすくなるからかな、と。

ただ、今回の件を良い機会として、
そもそも先頭にアンダースコアをつけるのは一般的なのか
ということをGoogle先生に訊ねてみましたが(20分くらい)、似た様な理由でついているケースが多いでしょうか。
あとは使っている言語と好みの問題かなという印象です。

もちろん言語それぞれに事情はあると思うので、単純に
「今後のプログラミングでは先頭アンダースコアは使わないぞ★」
なんてことは言いません。

ですが、ひとまずVue.jsを使うときは意識して抜いていこうと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?