開發一個vue組件(vue 開發環境已經搭建且容許使用單文件組件)

1、.vue文件css

<template>
  /** 這裏寫html代碼*/html

  <span>{{msg}}</span>
</template>vue

<script>
  import { xxxx } from 'xxx'
  export default {node

     // 生命週期鉤子express

    beforeCreate () {api

    },less

      created () {函數

    },ui

    beforeMount () {this

    },

    mounted () {

    },

    beforeUpdate () {

    },

    updated () {

    },

    activated () {

    },
    deactivated () {

    },

    beforeDestroy () {

    },
    destoryed () {

    },
    name: 'my-component',// 組件標籤
    components: {// 這裏能夠引入外部組件,而後template裏面使用所引入的組件
      Component1,
      Component2
    },
    model: {// v-model綁定的值會傳給這個prop,假如組件內部調用了這個方法,則v-model的值會改變。不定義的話v-model的屬性是value,方法是input
      prop: '屬性名',
      event: '方法'
    },
    data () {// 這裏定義這個組件裏面使用的屬性,能夠在script跟template裏面使用,一個地方變了兩位一個地方的值也會相應變換
      return {
        msg: '消息',

        allData: []
      }
    },
    props: {// 這裏是接收使用這個組件時,組件上面傳入的屬性
      data: {
        type: Array,
        required: true,
        default () {
          return []
        }
      },
      ‘v-model使用的屬性名’: {
        type: Array,
        required: false,
        default () {
          return []
        }
      },
    },
    watch: {// 監聽屬性的變化
      data: {
        deep: true,
        handler (val, oldVal) {
          if (val !== oldVal) {
            this.allData = this.formatData({ data: val, parentId: 'root' })

            this.$emit('v-model使用的方法', val)
          }
        }
      },
   },
   computed: {// 計算屬性,裏面的屬性的值變了的話,這個屬性會跟着變
     isShow() {
       return !!this.msg
     }
   },
   methods: {// 定義方法
     toggle (isShow = false) {
       this.isShow = isShow
     },
     formatData ({ data = [], parentId = '' } = {}) {
      return true
     },
  },

  mixins: [mixins],// 混入,mixins是vue實例對象的選項

  directives: {/** 在template可使用這裏的指令,使用的時候在前面加一個v-,有鉤子函數bind,unbind,inserted,update,componentUpdated。鉤子函數的參數有以下例子,binding是一個對象包含name, value, oldValue, expression, args, modifiers */

    focus: {

      inserted: function (el, binding, vnode, oldVnode) {

        el.focus()

      }

    }

  },

  filters: {在template可使用這裏的過濾器

    capitalize (value) {

      if (!value) {

        return ''

      }

      value = value.toString()

      return value.charAt(0).toUpperCase() + value.slice(1)

    }

  }
</script>

<style lang="less" scoped>

  /** 這裏能夠寫樣式,scoped使得這裏的樣式不會影響別的地方,lang=less使得這裏可使用less預處理css*/

</style>

 

2、使用上面定義的組件

<my-component v-model="aa" data="cc"></my-component>

變量aa跟cc要在當前腳本定義屬性。

相關文章
相關標籤/搜索