为什么 Vue 使用 template:'<app/>' 可以将 components 中的 app 插入至页面

在默认的示例项目中,我看到了它设置

template:'<app/>,
components:{
    App
}

就可以实现html 页面中不需要设置<app></app> 就可以加载 App
请问这是什么原理?

阅读 5.5k
2 个回答

说来话长,不如你去看一下我为 vuejs.org 贡献的 pull request:

https://github.com/vuejs/vuej...

该 pr 主要分为三部分——
关于 el 的:
If neither render function nor template option is present, the in-DOM HTML of the mounting DOM element will be extracted as the template. In this case, Runtime + Compiler build of Vue should be used.
关于 template 的:
If render function is present in the Vue option, the template will be ignored.
关于 render 的:
The render function has priority over the render function compiled from template option or in-DOM HTML template of the mounting element which is specified by the el option.

官网中文版也有翻译。

之所以添加该部分内容,是因为 https://segmentfault.com/q/10... 这个问题

如果换一种方式就更好理解 ,局部组件

<div id="app">
    <runoob></runoob>
</div>
 
<script>
var Child = {
  template: '<h1>自定义组件!</h1>'
}
 
// 创建根实例
new Vue({
  el: '#app',
  components: {
    // <runoob> 将只在父模板可用
    'runoob': Child
  }
})
</script> 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题