开发一个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要在当前脚本定义属性。

相关文章
相关标签/搜索