组件的发布与使用
2022/7/29原创大约 2 分钟约 599 字
創建項目
新建一个文件夹,用于保存组件的内容,我这里是MyGwc
终端输入npm init生成组件的json文件

package name 包名
version 版本
description 描述
entry point 入口点
test command 测试命令
git repository git存储库
keywords 关键字
author 作者
license 许可证

創建目錄
在MyGwc文件夹下创建assets文件夹和components文件夹
assets文件夹用于存放组件的CSS和js文件
components文件夹用于存放组件(MyGwc.vue)
index.js为组件的入口文件
組件代碼
<template>
<div>
<table v-if="list.length > 0">
<thead>
<tr>
<td>序号</td>
<td>商品名称</td>
<td>单价</td>
<td>数量</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in list" :key="(item, index)">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<button @click="reduce(index)" :disabled="item.count === 1">
-
</button>
{{ item.count }}
<button @click="add(index)">+</button>
</td>
<td @click="remove(index)">删除</td>
</tr>
</tbody>
<h1>总价:{{ totalPrice }}</h1>
</table>
<div v-else>暂无数据...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [
{
id: 0,
name: "牛奶",
price: 25,
count: 2,
},
{
id: 1,
name: "干脆面",
price: 15,
count: 5,
},
{
id: 2,
name: "篮球",
price: 156,
count: 1,
},
{
id: 3,
name: "篮球鞋",
price: 360,
count: 1,
},
{
id: 4,
name: "山地车",
price: 3850,
count: 1,
},
],
};
},
methods: {
add(index) {
this.list[index].count++;
},
reduce(index) {
// if (this.list[index].count == 1) return; //除此之外还能使用disables(禁用)属性
this.list[index].count--;
},
remove(index) {
this.list.splice(index, 1);
},
},
computed: {
totalPrice() {
let total = 0;
for (let i = 0; i < this.list.length; i++) {
total += this.list[i].price * this.list[i].count;
}
return total;
},
},
};
</script>
<style>
table {
border: 1px solid #f5f5f5;
}
tr,
td {
padding: 15px;
border: 1px solid #f5f5f5;
}
</style>
index.js
import info from '../../package.json'
import input from './pic-input'
import button from './pig-button'
const components=[input,button]
const install=function(Vue){
components.forEach((com)=>{
Vue.component(com.name,com)
})
Vue.prototype.$alert1=function(){
alert('msg')
}
}
//引用文件方式时,会使用,类似jquery方式引入
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
export default {
name: info.name,
author: info.author,
version: info.version,
description: info.description,
install
}
配置package.json
"package": "vue-cli-service build --target lib ./src/package/index.js --name bhg-ui --dest bhg-ui"
生成打包
npm run package
发布
- 终端输入npm login
- 根据提示输入你的npm账号密码和邮箱
- 進入打包目錄,執行
npm init -y
- 输入npm publish 发布到npm上
使用
npm install --save 插件名
註冊全局組件
main.js
import bhgUI from 'bhg-ui'
Vue.use(bhgUI)
頁面直接使用組件
使用插件
<template>
<div id="app">
<MyGwc></MyGwc>
</div>
</template>
<script>
import MyGwc from "itnh_shoppingcar/components/MyGwc";
export default {
name: "App",
components: {
MyGwc,
},
};
</script>