vueJS组件

来源:互联网 发布:python cxoracle 结果 编辑:程序博客网 时间:2024/06/05 04:53
什么是组件:组件是Vue.js最强大的功能之一。组件可以扩展HTML元素,封装可重用的代码。在较高层面上,组件是自定义的元素,Vue.js的编译器为它添加特殊功能。在有些情况下,组件也可以是原生HTML元素的形式,以is特性扩展。 如何注册组件? 需要使用Vue.extend方法创建一个组件,然后使用Vue.component方法注册组件。Vue.extend方法格式如下:var MyComponent = Vue.extend({ // 选项…后面再介绍}) 如果想要其他地方使用这个创建的组件,还得个组件命个名:Vue.component(‘my-component’, MyComponent) 命名之后即可在HTML标签中使用这个组件名称,像使用DOM元素一样。下面来看看一个完整的组件注册和使用例子。 html代码:
js代码:

复制代码
// 定义
var MyComponent = Vue.extend({
template: ‘

A custom component!

})

// 注册
Vue.component(‘my-component’, MyComponent)

// 创建根实例
new Vue({
el: ‘#example’
})
复制代码
输出结果:

A custom component!
A custom component!’});var parent = Vue.extend({ template: ‘
Parent Component:
‘, components: { ‘child-component’: child }});Vue.component(“parent-component”, parent);复制代码 上面的定义过程比较繁琐,也可以不用每次都调用Vue.component和Vue.extend方法:复制代码// 在一个步骤中扩展与注册Vue.component(‘my-component’, {template: ‘
A custom component!
’})// 局部注册也可以这么做var Parent = Vue.extend({ components: { ‘my-component’: { template: ‘
A custom component!
’ } }})复制代码 动态组件 多个组件可以使用同一个挂载点,然后动态的在他们之间切换。使用保留的元素,动态地绑定到它的is特性。下面的列子在同一个vue实例下挂了home、posts、archive三个组件,通过特性currentView动态切换组件显示。 html代码:复制代码
Home Posts Archive

复制代码
js代码:

复制代码
var vue = new Vue({
el:”#dynamic”,
data: {
currentView: “home”
},
components: {
home:{
template: “Home”
},
posts: {
template: “Posts”
},
archive: {
template: “Archive”
}
}
});
document.getElementById(“home”).onclick = function(){
vue.currentView = “home”;
};
document.getElementById(“posts”).onclick = function(){
vue.currentView = “posts”;
};
document.getElementById(“archive”).onclick = function(){
vue.currentView = “archive”;
};
复制代码
组件和v-for


不能传递数据给组件,因为组件的作用域是独立的。为了传递数据给组件,应当使用props:

原创粉丝点击