一直使用单文件的方式构建 Vue 项目,今天因为各种原因需要用非构建方式编写 Vue 代码,遇到一个问题:
比如 HTML 为:
<body>
<app>
<child></child>
</app>
</body>
JS 为:
// Child.
const Child = Vue.extend({
template: '<h1>This is the children.</h1>'
});
// App.
const App = Vue.extend({
data () {
return {...}
},
components: {
Child
}
});
// Root Instance.
Const Root = new Vue({
el: 'body',
components: { App }
});
这样写是找不到 child
的,不过好像有两种方法:
在
Root
中注册child
.(或全局注册)在
App
的template
中引入child
而不是 HTML 中.
但是如果用第一种方式, child
组件并不听从 app
组件内的 data,而是听从于 Root
中的 data,比如 <child :show="loading" v-if="loading"></child>
,传入的 loading 不是从 app
中来的而是从 Root
中的,这和用 单文件 + Webpack
组织的 Vue 项目行为完全不同;
至于第二个问题,如果想在 HTML 中写好组件标签而不是写到 template
中,这样是不可以的么?
希望各位能指点一二,感激不尽!
给 App 加上
inline-template
:这样就和 .vue 文件里的
<template></template>
行为一致了.参看:内联模板