本文主要是介绍Vue组件之入门:全局组件三种定义,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
不论我们使用哪种方式创建出来的组件,组件中的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模板的属性来展示组件要显示的htmltemplate: '<h2>使用Vue.extend创建全局组件</h2>'});//第二步:使用 Vue.component('组件名称',创建出来的组件模板对象)Vue.component('myCompnent', com1);// 创建 Vue 实例,得到 ViewModelvar 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 实例,得到 ViewModelvar 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>

这篇关于Vue组件之入门:全局组件三种定义的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!