ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[toc] ### 1. 使用Vue.extend来创建全局的Vue组件 1. 创建组件 2. 注册组件 注意:如果使用Vue.component定义全局组件时,组件名称使用了驼峰命名,则在引用组件的时候,需要把大写的驼峰改成小写的字母,同时,两个单词之间用`-`连接 ,如果不使用驼峰,则直接拿名称来使用即可 ``` // 1. 使用Vue.extend来创建全局的Vue组件 var com1 = Vue.extend({ // 通过template属性,指定了组件要展示的HTML结构 template: '<h3>这是使用Vue.extend创建的组件</h3>' }) // 2. 使用Vue.component('组件的名称', 创建出来的组件模板对象) Vue.component('mycom1', com1); // 3. 创建Vue实例,使用模板 var vm = new Vue({ el: '#app' }) ``` 3. 一步注册并创建组件 Vue.component(组件名,Vue.extend创件的组件(其中template就是要展示的HTML内容)) ``` Vue.component('mycom1', Vue.extend({ template: '<h3>这是使用Vue.extend创建的组件</h3>' })) ``` ### 2. 仅使用component创建 注意:不论是哪种方式创建出来的组件,组件的template属性指向的模板内容,必须有且只能有唯一的一个根元素 ``` Vue.component('mycom2', { template: '<div><h3>1</h3><span>2</span></div>' }) ``` ### 3. template与Vue.component分离(推荐) 通过template元素,在外部定义的组件结构,这个方式,有代码的智能提示和高亮,`template` 元素不需要放在Vue元素里 ``` <template id="temp1"> <h1></h1> <h4>推荐!</h4> </template> ``` ``` Vue.component('mycom3', { template: '#temp1' }) var vm = new Vue({ el: '#app' }) ``` ### 4. 通过对象字面量的形式,定义一个组件模板对象 ``` var login = { template: '<h1>1</h1> } Vue.component('mylogin', login); ```