我可以使用 Vue 和 Vue Router CDN 导入单个文件组件吗?

Can i import single file component using Vue and Vue Router CDN?

我目前正在使用 Vue 和 Vue Router CDN。我想使用 Vue 路由器将单个文件组件 (user.html) 导入到我的 index.html。但是当我点击 "Go to user" 时,数据没有显示。我阅读了一些关于 Vue 路由器的指南,但他们使用 NPM 或 CIL 而不是 Vue CDN。 Index.html

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- use router-link component for navigation. -->
    <!-- specify the link by passing the `to` prop. -->
    <!-- `<router-link>` will be rendered as an `<a>` tag by default -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
    <router-link to='/User.html'>Go to User</router-link>
  </p>
  <!-- route outlet -->
  <!-- component matched by the route will render here -->
  <router-view></router-view>
</div>
<script>
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const User = { template: '#test'}
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
{
  path:'/User.html', component: User
}
]

const router = new VueRouter({
routes 
})
const app = new Vue({
router
}).$mount('#app')
</script>

User.html

<template id = "test">
fsjdfjdfldskjflkd
</template>

我认为存在误会。据我所知,您正在尝试以加载 .vue 文件的方式加载 User.html,但这不起作用,除非您使用 Webpack 构建项目,因为 .vue filetype是vue-loader项目负责解析的东西。

Vue Router CDN 意味着您没有使用 Webpack 进行构建,因此不可能像您正在做的那样加载组件。您可以将 Vue Router 配置为提供 User.html 文件,但该文件不能是模板组件,因为在 CDN 模式下 Vue Router 不知道您的服务器上有什么文件,也不能简单地检索它们。

因此您需要执行以下三个选项之一:

选项 1:开始为您的项目使用 Webpack

这是我推荐你做的。您会发现您的项目将执行得更好并且使用它更容易开发。

选项 2:为 CDN 使用正确的模板语法

例如:

var mytemplate = `<div>
<h1>This is my template</h1>
</div>`

Vue.component('mycomp1', {
    template: mytemplate
});

Vue.component('mycomp2', {
    template: `
        <div>
            Hello, {{ name }}!
        </div>
    `,
    props: ['name'],
});

当您不使用 Webpack 进行构建时,您无法加载其他文件作为模板。 Webpack 为您将它们放入您的单页应用程序中,Vue Router 不知道里面有什么 User.html Vue 也不能将其用作模板。可以告诉 Vue Router 重定向到功能齐全的 User.html 网站页面,而不是仅仅将其用作模板。

选项 3:使用 Ajax 请求获取模板文件

我强烈建议您不要这样做,但是为了完整起见,如果您使用 Ajax 请求获取 User.html 文件的内容,则可以使用 CDN 版本,并且从中创建一个组件。

我真的真的建议你停止使用 CDN 版本,转而使用基于 Webpack 的解决方案,向黑暗面屈服!或者更简单,使用 Nuxt.js 代替,因为它更容易让初学者使用。