目录
- 什么是组件
- 好处
- 组件分类
- 定义组件和使用
- 注意事项
什么是组件:
一个按钮,一个输入框,都算一个组件,只不过是系统提供给我们的,我们需要自己的组件,如自定义弹框,轮播图
好处:
- 可复用性
- 可维护性
组件分类 :
- 独立组件:不依赖框架
- 框架通用组件:基于jquery,基于react,意思要引入某个框架才能正常用
定义组件和使用:
如弹框组件
定义组件
// popUp.css
popUp-alert {
/* 使用组件名前缀 命名类名*/
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.popUp-alert {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 500px;
height: 300px;
box-shadow: 0 0 12px rgba(0,0,0,.5);
border: 1px solid #000;
text-align: center;
line-height: 300px;
}
}
// PopUp.js
class PopUp {
static alert(
options = {
content: '',
title: '',
style: { width: 500, height: 300, x: 50, y: 50 },
handle: null,
hasCloseBtn: false
}) {
if (!$('.popUp-alert').length) {
let { content, style, handle, title, hasCloseBtn } = options,
box = $(`<div class="popUp-alert"><div class="popUp-title">${title}</div></div>`),
confirmBtn = $('<button type="button" class="popUp-confirm-btn">确定</button>');
box.css('width', `${style.width}px`);
box.css('height', `${style.height}px`);
box.css('left', `${style.x}%`);
box.css('top', `${style.y}%`);
box.css('line-height', `${style.height}px`);
if (hasCloseBtn) {
let closeBtn = $('<button type="button" class="popUp-close">X</button>');
box.append(closeBtn);
closeBtn.click(() => {
box.hide();
})
}
box.appendTo('body');
box.append(content);
box.append(confirmBtn);
confirmBtn.click(() => {
handle && handle();
box.hide();
})
} else {
$('.popUp-alert').show();
}
}
export default PopUp;
// 使用时直接引入即可,需使用构建工具打包,如webpack
// index.html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>组件化开发</title>
<link rel="stylesheet" href="popUp.css">
</head>
<body>
<button id="alert">alert</button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="bundle.js"></script>
</body>
</html>
// bundle.js
import PopUp from './popUp';
$('#alert').click(()=>{
PopUp.alert({content: 'welcome!',title:'提示',style:{width: 300,height:200},hasCloseBtn: false});
})
注意事项
- 使用模块化开发
- 设计组件时考虑提供哪些接口进行配置
webpack打包模板
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: '../'
}
},
"css-loader"
]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './index.html',
})
],
};
网友评论