Vue组件
组件(Component)是Vue.js最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。所有的 Vue 组件同时也都是 Vue 的实例,所以可接受相同的选项对象 (除了一些根级特有的选项) 并提供相同的生命周期钩子。
使用方法:
Vue.component(组件名称, 组件的内容)
例如:
Vue.component('component',{
template:'<div>这是div标签</div>'
})
注册及使用组件
<div id="example">
<!--使用组件-->
<my-component></my-component>
</div>
<script>
// 注册一个组件:
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
new Vue({
el: '#example'
})
</script>
data 必须是函数
组件中的 data 是一个函数, vue 对象中的data是一个对象
组件就是 vue 的实例,所有 vue 实例中属性和方法,组件中也可以用,但是 data 属性必须是一个函数,因为组件会重复使用在多个地方,为了使用在多个地方的组件数据相对独立,data属性需要用一个函数来返回值。
<div id="example-2">
<!--使用组件-->
<simple-counter></simple-counter>
<simple-counter></simple-counter>
<simple-counter></simple-counter>
</div>
<script>
// 定义组件
Vue.component('simpleCounter', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
}
})
new Vue({
el: '#example-2'
})
</script>
props传递数据
这个属性一般用来给组件传递值使用的
如果想给组件中传递参数,组件要显式地用 props 选项声明它预期的数据:
<div id="app">
<my-component name="zhangsan"></my-component>
</div>
<script>
Vue.component('myComponent',{
template:'<div>哈哈哈{{name}}</div>',
props:['name']
})
var vm = new Vue({
el:'#app'
})
</script>
结果:
哈哈哈zhangsan
单文件组件
将一个组件相关的 html 结构,css 样式,以及交互的 JavaScript 代码从 html 文件中剥离出来,合成一个文件,这种文件就是单文件组件,相当于一个组件具有了结构、表现和行为的完整功能,方便组件之间随意组合以及组件的重用,这种文件的扩展名为“.vue”,比如:”menu.vue”。
单文件组件代码结构
<template>
<!--使用template标签来定义html部分-->
<div class="breadcrumb" @click="fnLight">
当前位置:<span :class="{hot:isHot}">{{pos}}</span>
</div>
</template>
<script>
// javascript要写成模块导出的形式:
export default {
props:['pos'],
name:'breadcrumb',
data:function(){
return {
isHot:false
}
},
methods:{
fnLight:function(){
this.isHot = !this.isHot;
}
}
}
</script>
<style scoped>
/* 样式中如果有scope关键字,表示这些样式是组件局部的,不会影响其他元素 */
.breadcrumb{
width:90%;
line-height:50px;
border-bottom:1px solid #ddd;
margin:0px auto;
}
.breadcrumb .hot{
font-weight:bold;
color:red;
letter-spacing:2px;
}
</style>