不论我们使用哪种方式创建出来的组件,组件中的template属性指向的模板内容中,必须有且只有一个根元素,其他元素必须在这个根元素下面。

1.使用Vue.extend配合Vue.component定义全局组件

    在使用Vue.extend配合Vue.component定义全局组件时,Vue.extend里面定义template模板,而
Vue.component里面是要注册一个组件。
<body> <div id="app"> <!--第三步页面中使用 --> <!--
如果要使用组件,直接把组件的名称以HTML标签的形式引入到页面中--> <my-compnent></my-compnent> </div> <script>
//第一步:使用Vue.extend来创建全局组件 var com1 = Vue.extend({
//通过template模板的属性来展示组件要显示的html template: '<h2>使用Vue.extend创建全局组件</h2>' });
//第二步:使用 Vue.component('组件名称',创建出来的组件模板对象) Vue.component('myCompnent', com1);
// 创建 Vue 实例,得到 ViewModel var vm = new Vue({ el: '#app', data: {}, methods: {}
}); </script> </body>
【注意】在定义注册组件时,组件的名称不需要按照驼峰命名,但是在页面引入组件时,组件的名称必须按照驼峰命名。

简写如下:

2.直接使用Vue.component定义全局组件

这里是直接使用Vue.component直接创建一个组件
<div id="app"> <my-com2></my-com2> </div> <script> Vue.component('myCom2', {
template: '<h2>直接使用Vue.component创建组件</h2>' }); // 创建 Vue 实例,得到 ViewModel var vm
= new Vue({ el: '#app', data: {}, methods: {} }); </script>
3.Vue外部直接定义template

 
<body> <div id="app"> <my-com3></my-com3> </div> <template id="tmp1"> <div>
<h2>这是通过template元素,在外部定义组件的结构,有代码的提示和高亮</h2> </div> </template> <script>
Vue.component('myCom3', { template: "#tmp1" }); var vm = new Vue({ el: '#app',
data: {}, methods: {} }); </script> </body>

技术
今日推荐
PPT
阅读数 126
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信