Vue组件用法

组件(Component)是Vue.js最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。所有的 Vue 组件同时也都是 Vue 的实例,所以可接受相同的选项对象 (除了一些根级特有的选项) 并提供相同的生命周期钩子。

注册及使用组件

// 注册一个组件:
Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})

//使用组件
<div id="example">
  <my-component></my-component>
</div>
......

new Vue({
  el: '#example'
})

data 必须是函数

组件就是vue的实例,所有vue实例中属性和方法,组件中也可以用,但是data属性必须是一个函数,因为组件会重复使用在多个地方,为了使用在多个地方的组件数据相对独立,data属性需要用一个函数来返回值。


// 定义组件
Vue.component('simple-counter', {
  template: '<button v-on:click="counter += 1">{{ counter }}</button>',
  data: function () {
        return {
        counter: 0
      }
  }
})

// 使用组件
<div id="example-2">
  <simple-counter></simple-counter>
  <simple-counter></simple-counter>
  <simple-counter></simple-counter>
</div>
......
new Vue({
  el: '#example-2'
})

props传递数据

如果想给组件中传递参数,组件要显式地用 props 选项声明它预期的数据:

<!-- 样式 -->
<style>
    .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>

......
<div id="app">
    <bread-crumb pos="首页&gt;图片列表"></bread-crumb>
</div>

<script>
    Vue.component('bread-crumb',{
        props:['pos'],
        template:'<div class="breadcrumb" @click="fnLight">当前位置:<span :class="{hot:isHot}">{{pos}}</span></div>',
        data:function(){
            return {
                isHot:false
            }
        },
        methods:{
            fnLight:function(){
                this.isHot = !this.isHot;
            }
        }
    })
    let vm = new Vue({
        el:'#app'
    })
</script>

单文件组件

将一个组件相关的html结构,css样式,以及交互的JavaScript代码从html文件中剥离出来,合成一个文件,这种文件就是单文件组件,相当于一个组件具有了结构、表现和行为的完整功能,方便组件之间随意组合以及组件的重用,这种文件的扩展名为“.vue”,比如:"menu.vue"。

单文件组件代码结构

// 使用template标签来定义html部分
<template>
<div class="breadcrumb" @click="fnLight">
  当前位置:<span :class="{hot:isHot}">{{pos}}</span>
</div>
</template>

// javascript要写成模块导出的形式:
<script>
export default{
  props:['pos'],
  name:'breadcrumb',
  data:function(){
      return {
          isHot:false
      }
  },
  methods:{
      fnLight:function(){
          this.isHot = !this.isHot;
      }
  }
}
</script>

// 样式中如果有scope关键字,表示这些样式是组件局部的,不会影响其他元素
<style scoped>
.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>

猜你喜欢

转载自blog.csdn.net/weixin_31449201/article/details/82053949