创建组件
使用Vue的静态方法extend可以定义全局组件,然后通过Vue的静态方法component实例化一个组件,最后将组件的名称以html标签的形式插入vue对象所关注的那个父元素里。
<body>
<div id="box">
<mycom></mycom> //vue组件必须放入vue对象所关注的那个父元素里
</div>
</body>
<script>
//定义组件
var com1 = Vue.extend({
template:"<h3>hello</h3>" //模板元素只能由一个root元素,如果还有其它html元素,则必须放入根元素里
});
//创建组件实例
Vue.component("mycom", com1); //如果组件实例的名字是驼峰形式的,则插入html组件标签时必须像这样:Vue.component("myCom", com1);<my-com></my-com>
var vm = new Vue({
el: "#box"
});
</script>
<div id="box">
<mycom></mycom> //vue组件必须放入vue对象所关注的那个父元素里
</div>
</body>
<script>
//定义组件
var com1 = Vue.extend({
template:"<h3>hello</h3>" //模板元素只能由一个root元素,如果还有其它html元素,则必须放入根元素里
});
//创建组件实例
Vue.component("mycom", com1); //如果组件实例的名字是驼峰形式的,则插入html组件标签时必须像这样:Vue.component("myCom", com1);<my-com></my-com>
var vm = new Vue({
el: "#box"
});
</script>
组件字面量
使用字面量来创建组件
Vue.component("mycom", {
template: "<h3>hello</h3>"
});
template: "<h3>hello</h3>"
});
外部创建模板,把外部模板引入组件
<div id="box">
<mycom></mycom>
</div>
<template id="tem">
<h3>hello</h3>
</template>
Vue.component("mycom", {
template: "#tem"
});
<mycom></mycom>
</div>
<template id="tem">
<h3>hello</h3>
</template>
Vue.component("mycom", {
template: "#tem"
});
创建私有组件
var vm = new Vue({
el: "#box",
components: {
mycom: {
template:"<h3>hello</h3>"
}
}
});
el: "#box",
components: {
mycom: {
template:"<h3>hello</h3>"
}
}
});
组件内部的数据存储
组件也可以定义类似于vue对象内部的data属性,用于存储一些变量数据,在组件中的data属性必须是一个函数且必须返回一个匿名对象,所有数据可以定义在该匿名对象中。不要返回外部的对象,必须是匿名对象,以防止出现错误。
var com=Vue.extend({
template: "<h3>{{msg}}</h3>",
data: function () {
return {
msg:"hello world"
}
}
});
Vue.component("mycom",com);
template: "<h3>{{msg}}</h3>",
data: function () {
return {
msg:"hello world"
}
}
});
Vue.component("mycom",com);
组件的切换
类似于tab的切换项,利用vue提供的componenthtml标签来实现
<div id="box">
<a href="#" @click="login">login</a>
<a href="#" @click="register">register</a>
<component :is="componentName"></component>
</div>
<script>
Vue.component("login", {
template: "<h3>login区域</h3>"
});
Vue.component("register", {
template: "<h3>register区域</h3>",
});
var vm = new Vue({
el: "#box",
data: {
componentName:null
},
methods: {
login: function () {
this.componentName = "login";
},
register: function () {
this.componentName = "register";
}
}
});
<a href="#" @click="login">login</a>
<a href="#" @click="register">register</a>
<component :is="componentName"></component>
</div>
<script>
Vue.component("login", {
template: "<h3>login区域</h3>"
});
Vue.component("register", {
template: "<h3>register区域</h3>",
});
var vm = new Vue({
el: "#box",
data: {
componentName:null
},
methods: {
login: function () {
this.componentName = "login";
},
register: function () {
this.componentName = "register";
}
}
});