在做基于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';
好了,按照这方式通用组件管理就很方便了。