如何将 vue 与 .vue 文件一起使用

问题描述 投票:0回答:1

Vue 只是用 javascript 操作 html。基本上,您创建一个 vue 对象,然后将该对象安装在带有 id 的 div 上。我想测试我创建一个 .vue 文件并将此 .vue 文件导入到 js 文件中,然后将其安装在 div 上。但它失败了。这个项目只是为了尝试。这是我的项目架构。

App.vue 内容:

<template>
<h1>{{ msg }}</h1>
<h1>.Vue file</h1>
</template>
<script>
export default{
    name: 'App',
    data(){
        return{
            msg: 'VUE JS 3'
        }
    }
}
</script>

app.js 内容:

import App from './App.vue';
const app = Vue.createApp(App);

app.mount('#app');

index.html 内容:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue Basics</title>
    <link
      href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <script src="https://unpkg.com/[email protected]/dist/vue.global.js" defer></script> 
    <script src="app.js" defer></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

在 Chrome 控制台中输出是

当我将 type="module" 添加到 app.js 输出的脚本标签时:

当我将 type="module" 更改为 type="application/octet-stream" 时,控制台中没有错误,但网页上没有任何错误。 我认为我无法导入 .vue 文件,或者导入时 .vue 文件不起作用,但为什么?

javascript html vue.js vuejs3
1个回答
0
投票

您可以通过指定包含

<template>
组件 HTML 的
App
来模拟这一点。并将其注入到
#app
DOM 元素中。

// Grab the template HTML content, and insert it into the #app div's HTML
const app = document.querySelector('#app').insertAdjacentHTML('beforeend',
  document.querySelector('[data-id="App"]').innerHTML);

/** App.js */
const { ref } = Vue;
const App = {
  setup() {
    const msg = ref('VUE JS 3');
    return { msg };
  }
}

// Mount the App on the #app div in the DOM
Vue.createApp(App).mount('#app');
<!-- App.vue -->
<template data-id="App">
  <p>{{msg}}</p>
  <input v-model="msg">
</template>
<div id="app"></div>
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.