手把手教你开发 Vue 组件 ( 一)

很久没写文章啦~
新公司有点忙, 再加上最近在写 node.js, 抽空写一篇吧! javascript

随着 Vue 愈来愈火热, 相关组件库也很是多啦, 只用轮子怎么够, 仍是要造起来!!!
滴滴公共前端团队已经有了一篇文章 [Vue] 插件开发入门
可是可能具体细节还不够清楚; 在本文中; 将带领你们开发一个简单的分页组件~css

1 环境配置

首先使用 vue-cli 脚手架, 生成基本项目;html

npm install vue-cli -g
# mvue 是本次项目名称
vue init webpack mvue复制代码

若是要开发一个 npm 安装包, 还修改 package.jsonmain 选项前端

"main": "dist/mvue.js"复制代码

意思是咱们将提供编译压缩后 mvue.js 文件给其余开发者使用;vue

2. webpack

在前端领域内, 可谓是没 webpack 不成活; 手写太麻烦, 就直接给你们文件了, 如下是咱们的 webpack.config.js 文件:java

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: {
        main: './src/mvue.js'
    },
    output: {
        path: path.resolve(__dirname, '../dist'),
        publicPath: '/dist/',
        filename: 'mvue.js',
        library: 'mvue',
        libraryTarget: 'umd',
        umdNamedDefine: true
    },
    externals: {
        vue: {
            root: 'Vue',
            commonjs: 'vue',
            commonjs2: 'vue',
            amd: 'vue'
        }
    },
    resolve: {
        extensions: ['', '.js', '.vue']
    },
    module: {
        loaders: [{
            test: /\.vue$/,
            loader: 'vue'
        }, {
            test: /\.js$/,
            loader: 'babel',
            exclude: /node_modules/
        }, {
            test: /\.css$/,
            loader: 'style!css!autoprefixer'
        }, {
            test: /\.less$/,
            loader: 'style!css!less'
        }, {
            test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
            loader: 'url?limit=8192'
        }, {
            test: /\.(html|tpl)$/,
            loader: 'vue-html'
        }]
    },
    plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: '"production"'
            }
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new webpack.optimize.OccurenceOrderPlugin()
    ]
}复制代码

重点是 entry 和 output, 指定入口文件和输出文件;
由于咱们要写的是分页组件, 因此已经在 components 目录下建立了 page.vue;
接下来 咱们编写 webpack 入口文件:node

import Page from './components/page';

const mvue = {
  Page
};

// 导出 install 函数
// Vue.use() 会调用这个函数
const install = function(Vue, opts = {}) {
  // 若是安装过就忽略
  if (install.installed) return;

  // 指定组件 name
  Vue.component(Page.name, Page);
}

// 自动安装 方便打包成压缩文件, 用<script scr=''></script>的方式引用
if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue);
}

// 把模块导出
module.exports = {
  install,
  Page
}复制代码

在入口文件中, 咱们提供了对外公开的组件, install 函数, install 在 vue 组件开发中相当重要, vue 组件的调用方式是 Vue.use(***), 这个函数就会调用组件的 install 函数;
接下来就是各类组件的编写了!
以分页组件为例子, 首先咱们要指定 props, 并对其类型进行验证,webpack

props: {
    current: {
      type: Number,
      default: 1
    },
    total: {
      type: Number,
      default: 1
    }, 
    currentChange: {
      type: Function
    }
  }复制代码

一共接受三个参数 分别是:git

当前索引, 总条目, 回调函数github

export default {
  name: 'mvue-page',
  props: {
    current: {
      type: Number,
      default: 1
    },
    total: {
      type: Number,
      default: 1
    }, 
    currentChange: {
      type: Function
    }
  },
  mounted () {
    this.insertPage()
  },

  data () {
    return {
      currentIndex: this.current,
      pageShowArray: [],
      displayCount: 7
    }
  },

  methods: {
// 翻页
    insertPage () {
      let self = this
      self.pageShowArray = []

      for (var i = 1; i <= self.total; i++) {
        this.pageShowArray.push(i)
      }
      // 小型分页
      if (this.total <= this.displayCount) { return; }
      let begin = this.currentIndex - 3 
      let end = this.currentIndex + 3

      begin = begin <= 1 ? 1 : begin
      end = end <= this.displayCount ? this.displayCount : end
      begin = begin >= this.total - this.displayCount ? this.total - this.displayCount : begin
      end = end >= this.total ? this.total : end

      let arr = this.pageShowArray.slice(begin - 1, end)
      this.$set(this, 'pageShowArray', arr)
    },

// 上一页
   pre () {
      if (this.currentIndex <= this.displayCount) {return;}
      this.setIndex(this.currentIndex - this.displayCount)
      this.insertPage()
    },
// 下一页
    next () {
      if (this.currentIndex >= this.total) {return;}
      this.setIndex(this.currentIndex + this.displayCount)
      this.insertPage()
    },
// item 点击
    itemClick (current) {
      this.setIndex(current)
      this.insertPage()
// 触发回调
      this.currentChange(current)
    },
    setIndex (current) {
      let temp = current
      if (temp <= 1) { temp = 1}
      if (temp >= this.total) { temp = this.total}
      this.$set(this, 'currentIndex', temp)
    }
  }
}复制代码

调用方式

...  html code
<mvue-page :current="2" :total="40" :currentChange='currentChange'></mvue-page> ... js code // 两种方式选一个便可 // 按需加载 import {Page} from 'mvue' Vue.use(Page) // 所有加载 import mvue from '../dist/mvue.js' Vue.use(mvue);复制代码

如上, 一个简单的分页组件已经有些模样, 接下来使用 webpack 打包;

// 对应 config 文件
webpack webpack.config.js复制代码

发布

npm publish复制代码

若是有问题, 请在文本下面评论留言, O(∩_∩)O谢谢

相关代码 : github.com/ericjjj/mvu…欢迎 Star

相关文章
相关标签/搜索