Vue组件的发布与使用
第一步:
新建一个文件夹,用于保存组件的内容,我这里是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为组件的入口文件
MyGwc.vue
<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 MyGwc from "./components/MyGwc.vue";
export default {
install: (app, option) => {
app.component("MyGwc", MyGwc);
},
};
这样一来组件就算开发好了,接下来就是发布到npm上
第三步:
第四步:
终端输入npm install --save itnh_shoppingcar 下载依赖包(创建/组件)
2.使用插件
<template>
<div id="app">
<MyGwc></MyGwc>
</div>
</template>
<script>
import MyGwc from "itnh_shoppingcar/components/MyGwc";
export default {
name: "App",
components: {
MyGwc,
},
};
</script>
这样就可以了