gpt4 book ai didi

javascript - 导入单文件组件 VueJS

转载 作者:搜寻专家 更新时间:2023-10-30 22:34:12 27 4
gpt4 key购买 nike

每个人。

我对制作 vue 组件有一个微不足道的疑问。

我不想使用 browserifywebpack ,因为我在 django 工作,它的大部分模板都在静态文件中,虽然我读到 this ,它确实描述了如何同时考虑这两者(但那是另一天的事了)。

问题:

我正在制作一个单个文件组件,我必须使用我的路由器导入和使用它,但我不能,因为导入根本没有发生。

我的Hello.vue

<template>
Some HTML code here.
</template>
<script>
module.exports = {
data() {
return {
coin : []
}
},
beforeRouteEnter (to, from, next) {
axios.get('my-django-rest-api-url')
.then(response => {
next(vm => {
vm.data = response.data
})
})
}
}
</script>

我在 index.html 文件中有它,没有其他 .js 文件,

<script>
import Hello from '@/components/Hello.vue'
Vue.use(VueRouter);
const dashboard = {template:'<p>This is the base template</p>'};
const profile = {
template: '#profile_template',
data () {
return {
profile_details: []
}
},
beforeRouteEnter (to, from, next) {
axios.get('my-api-url')
.then(response => {
next(vm => {
vm.profile_details = response.data
})
})
}
}
const router = new VueRouter({
routes: [
{ path: '/', component: dashboard },
{ path: '/profile', component: profile },
{ path: '/hello', component: Hello }
]
});
new Vue({
router : router,
}).$mount('#app');
</script>

我都试过了:

1. <script src="../components/Hello.js" type="module"></script> 并按照建议删除导入语句 here

  1. 将我的 Hello.js 代码替换为:export const Hello = { ...
  2. 制作一个 Hello.js 文件并像这样导入它 import Hello from '../components/Hello.js';

错误:

  1. **Mozilla(Quantum 57.0.4 64 位)**:SyntaxError: import declarations may only appear at top level of a module
  2. **Chrome(63.0.3239.108(官方构建)(64 位))**:Uncaught SyntaxError: Unexpected identifier
附言: 我试过各种组合

最佳答案

不是 Vue.js 大师,但这里有一些可能对您有所帮助的观点。

  • 模块加载仍然是not supported on modern browsers by default ,并且您需要设置特殊标志才能启用它(您的应用程序的用户可能不会这样做)。
  • 如果你坚持使用importexport ,你需要 Webpack。当然还有 Babel(或任何其他 ES6 转译器,例如 Buble)。
  • 如果你愿意 module.exports ,那么你需要 Browserify。它支持浏览器环境中的 CommonJS。
  • 如果两者都不可行,那么最好的办法是在全局范围内定义 Vue 组件。您可以将它们拆分成单独的文件,并使用 <script> 导入每个文件个别地。绝对不是最干净的方法。
  • 单个文件组件通常位于 .vue 中文件,但无论哪种方式,它们都需要 vue-loader可以使用 bundler 添加和配置(再次)。
  • 最后一个选择是只使用现有的设置,如果有的话(有吗?)。如果您已经安装了 RequireJS、UMD 或类似的东西,请调整您的组件以适应它。否则,使用 <script> s.

关于javascript - 导入单文件组件 VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48269225/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com