全局组件定义的三种方式
- 使用 Vue.extend 配合 Vue.component 方法:
var login = Vue.extend({
template: '<h1>登录</h1>'
});
Vue.component('login', login);
- 直接使用 Vue.component 方法:
Vue.component('register', {
template: '<h1>注册</h1>'
});
- 将模板字符串,定义到script标签种:
<script id="tmpl" type="x-template">
<div><a href="#">登录</a> | <a href="#">注册</a></div>
</script>
同时,需要使用 Vue.component 来定义组件:
Vue.component('account', {
template: '#tmpl'
});
注意: 组件中的DOM结构,有且只能有唯一的根元素(Root Element)来进行包裹!
<div id="app">
<!-- 如果要使用组件,直接,把组件的名称,以HTML标签的形式,引入到页面中,即可 -->
<!-- <my-com1></my-com1> -->
<mycom1></mycom1>
</div>
<script>
// 1.1使用Vue.extend来创建全局的Vue组件
// var com1 = Vue.extend({
// template:'<h3>这是使用Vue.extend创建的组件</h3>'//通过template属性,指定了组件要展示的HTML结构
// })
//1.2使用Vue.component('组件的名称',创建出来的组件模板对象)
// Vue.component('myCom1',com1)
//如果使用Vue.conponent 定义全局组件的时候,组件名称使用了驼峰命名,则在引用组件的时候,需要把大写的驼峰改为小写的字母,同时,另个单词之间使用-连接
//如果不使用驼峰在,则直接拿名称来使用即可。
// Vue.component('mycom1',com1)
// Vue.component第一个参数:组件的名称,将来在引用组件的时候,就是一个标签形式来引用它的
//第二参数:Vue.extend创建的组件,其中template 就是组件将来要展示的HTML内容
Vue.component('mycom1',Vue.extend({
template:'<h3>这是使用Vue.extend创建的组件</h3>'//通过template属性,指定了组件要展示的HTML结构
}))
</script>