使用vue开发基于npm管理的通用模块

在做基于nodejs开发的vuejs时,经常会有一些公共组件,这些组件在多个vue项目中使用copy代码肯定不是很好的办法,应该做成跟vuex一样独立的模块,通过npm install引入就可以使用。

下面把我的经验简单的介绍:

内容的主题:

首先扩展一个input表单组件,然后通过npm发布到私有库,最后被使用。

1、使用vue-cli脚手架生成一个简单的webpack工程,作为通用组件x-input的工程;

> vue init webpack-simple x-input

2、工程生成好,npm install下载相关依赖;现在在src目录下新建一个x-input.vue的文件;

<template lang="html">
  <div class="input">
    <span>{{title}}</span>
    <div><input v-model="name"></div>
  </div>
</template>

<script>
export default {
  props: {
    title: String,
    name: String
  }
}
</script>
<style lang="css">
.input {
  width: 100%;
  height: 40px;
  line-height: 40px;
}
.input span {
  width: 20%;
  max-width: 200px;
}
.input div {
  float: right;
  width: 80%;
}
input {
  width: 100%;
  min-width: 200px;
  max-width: 500px;
  height: 40px;
}
</style>

可以在app.vue中测试下,import XInput from './x-input.vue';

<template>
  <div id="app">
    <x-input title="用户名" :name="username"></x-input>
  </div>
</template>

<script>
import XInput from './x-input.vue'
export default {
  name: 'app',
  components: {
    XInput
  },
  data () {
    return {
      username: ''
    }
  }
}
</script>

<style lang="scss">

</style>

启动服务看看 npm run dev;没问题我们开始发布这个工程

3、发布x-input

首先需要登录npm;提示需要输入用户密码邮箱,

> npm login
Username: admin
Password: 
Email: (this IS public):admin@bjnja.com
Logged in as admin on http://npm.bjnja.com/.

完成后提示登录成功,然后使用npm publish发布,npm每次发布版本号必须改变。

> npm publish

成功后会提示发布的版本号;

4、使用

现在怎么使用呢,新建一个vue工程;一样通过vue-cli创建;

> vue init webpack-simple my-project

安装x-input;

> npm install --save x-input

现在我们可以在my-project工程src目录App.vue中使用

<template>
  <div id="app">
    <x-input title="用户名" :name="username"></x-input>
  </div>
</template>

<script>
import XInput from 'x-input/src/x-input'
export default {
  name: 'app',
  components: {
    XInput
  },
  data () {
    return {
      username: ''
    }
  }
}
</script>

<style lang="scss">

</style>

通过引用的工程目录应用,很不方便;现在调整下;

5、通用模块主出口

在x-input工程根目录新疆index.js文件

import XInput from './src/x-input'

export {
  XInput
}

package.json文件设置入口:

"version": "1.0.1",
"main": "index.js",

版本调整,重新发布;

现在使用就好看多了,可以这么用:

import { XInput } from 'x-input';

好了,按照这方式通用组件管理就很方便了。

转载于:https://my.oschina.net/Lady/blog/1556007

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值