Vue 3 の <script setup> で this が使えない
<script setup> はモジュールスコープで実行されるため Options API の this が存在しない。
テンプレート参照は ref、props は defineProps、ライフサイクルは onMounted などの import 関数で置き換える。
公開: 更新:
node run.mjs Bad.vue TypeError: Cannot read properties of undefined (reading 'msg') focused element: BODY
2026-10-09 に node:20(Node.js 20.20.2 / npm 10.8.2) で実際に打って取った出力。検証環境の詳細
要約
<script setup> で書かれた SFC は内部的にコンポーネントの setup() 関数として動き、トップレベルがモジュールスコープになる。
Options API のような暗黙の this は存在しないため、ライフサイクル・props・emit・refs・ルーターはすべて Composition API の import 関数で取り替える必要がある。
実行例
Vue 3.5.43 を入れた node:20 のコンテナ(jsdom 上で描画)で試すと、<script setup> の中で this.msg を読む Bad.vue は TypeError: Cannot read properties of undefined (reading 'msg') になり、フォーカスも input に移らなかった。defineProps / defineEmits / ref / onMounted に置き換えた Good.vue は、update イベントで HELLO が発行され、フォーカスが input に移った。
$ node run.mjs Bad.vue
TypeError: Cannot read properties of undefined (reading 'msg')
focused element: BODY$ node run.mjs Good.vue
emitted update: HELLO
focused element: INPUT— 2026-10-09 時点の出力
検証環境Node.js 20.20.2 / npm 10.8.2 / Python 3.11.2 / 2026-10-09 検証(ほか 2 件)
- 検証日
- 実行環境
node:20Debian GNU/Linux 12 (bookworm)- バージョン
- Node.js 20.20.2
- npm 10.8.2
- Python 3.11.2
- Git 2.39.5
- Vue 3.5.43
この記事の「実行例」は、上記の環境で実際にコマンドを実行して得られた出力をそのまま掲載しています。 再現手順はリポジトリの検証スクリプトとして管理し、定期的に再実行して出力を更新しています。
解決策
1. テンプレート参照は ref で受ける
<script setup lang="ts">
import { ref, onMounted } from 'vue'
const inputRef = ref<HTMLInputElement | null>(null)
onMounted(() => {
inputRef.value?.focus()
})
</script>
<template>
<input ref="inputRef" />
</template>テンプレート側の ref="inputRef" 属性名と、<script setup> 内の変数名を一致させる。
2. props と emit はコンパイラマクロを使う
<script setup lang="ts">
const props = defineProps<{ msg: string }>()
const emit = defineEmits<{ (e: 'update', value: string): void }>()
function onInput(v: string) {
emit('update', v)
}
</script>defineProps / defineEmits はコンパイラマクロのため import 不要で、<script setup> 内に直接書ける。
詳細は 公式の <script setup> リファレンス(新しいタブで開く) を参照。
3. ライフサイクルは onMounted などをインポート
import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log('mounted')
})
onUnmounted(() => {
console.log('unmounted')
})Options API の mounted() / beforeUnmount() などは、すべて on* 関数として個別にインポートする。
4. ルーターは useRoute / useRouter
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
function goHome() {
router.push('/')
}Composition API では this.$route / this.$router は使えない。
各コンポーザブル経由で取得する。
よくある原因
- Options API から移行する際、
mounted()を<script setup>に貼り付けてthis.$elを参照している definePropsを書かずにthis.fooで props にアクセスしようとしているthis.$emit('change', val)を書いて TypeScript がany推論のままになり、実行時にTypeError: Cannot read properties of undefinedが出るvue-routerのナビゲーションをthis.$router.push(...)の感覚で書いている