Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

【求回答】javaScriptに記載していたVue情報を、vueファイルに記載すると動作しなくなった件

解決したいこと

Vue.jsの学習中に以下の事象が発生したため、これを解決したい。
タイトルがおかしいかもしれないが、許してほしい。

◆概要
 vue.jsファイルを読み込もうとしたが、うまく表示されない。

◆環境
 VSCode
(拡張機能のLive Serverで実行中)

1-1. 出来ているところ

1.JavaScriptファイルにVue.jsの内容を直書きし、表示させる。

demo.html
<!DOCTYPE html>
<html lang ="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv = "X-UA-Compatible" content = "IE=edge">
    <meta name = "viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
    <link rel="stylesheet" href="css/main.css">
</head>    
<body>

    <div id="app">
        <p>{{message}}</p> <!--messageの内容が表示されている。-->
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@3.2/dist/vue.global.js"></script>
    <script>console.log(Vue);</script>
    <script src="js/main.js"></script>
</body>
</html>
main.js
const app = Vue.createApp({
    data:() => ({
        message:'hello'
        }
    }
})
app.mount('#app')

1-2. 結果

image.png

2-1. エラーが発生する箇所

今度は、Vue.jsファイルに記載したものを読み込もうと、
testVue.vueを作成して以下のように記載した。

testVue.vue
<template>
    <div id="testVue">
        <p>テストですよ</p>
    </div>
</template>

<script>
    export default Vue.defineComponent({
        name: 'testVue',
    })
</script>
main.js
const app = Vue.createApp({
    data:() => ({
        message:'hello'
        }
    }
})
app.mount('#app')

//ここから追加要素
import testVue from './testVue.vue';
const app2 = Vue.createApp(testVue).mount('#app2');
Demo.html
<!DOCTYPE html>
<html lang ="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv = "X-UA-Compatible" content = "IE=edge">
    <meta name = "viewport" content="width=device-width, initial-scale=1.0">
    <title>Demo</title>
    <link rel="stylesheet" href="css/main.css">
</head>    
<body>

    <div id="app">
        <p>{{message}}</p> <!--messageがマウントされなくなった。-->
    </div>

    <!--ここから2行が追加要素-->
    <div id="app2">
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@3.2/dist/vue.global.js"></script>
    <script>console.log(Vue);</script>
    <script src="js/main.js"></script>
</body>
</html>

Vue.jsで作成したものが反映されていないどころか、
もともと動いていた箇所まで反映されなくなった。
(当然ながら、上記で追加したものを削除すると、
 元々うまく動いていた箇所は正常通り動作する。)
image.png

自分で試したこと

スペルやファイルの配置場所については、正しいことを確認しました。
他記事を探したり、chatGPTに聞いても解決しなかったため、
こちらで伺いたく思い、質問いたしました。

0 likes

1Answer

そもそもこれは動くのでしょうか……?
js の構文としてミスっていませんでしょうか?

main.js
const app = Vue.createApp({
    data:() => ({
        message:'hello'
        }
    }
})
app.mount('#app')

正しくはこうだったりしますでしょうか?

main.js
const app = Vue.createApp({
    data:() => ({
        message:'hello'
        }),
})
app.mount('#app')

import する為には script タグに type="module" を付けて esmodule モードで動かす必要があります。

また、 標準の js では .vue をそのまま import することに対応しておりません。(本来は サーバーサイドでjsに変換する処理が必要です。

1Like

Your answer might help someone💌