一、创建组件
1、在根目录下自定义一个components文件夹,用来存放自定义的组件。
2、再针对每一个组件创建一个文件夹,用来存放这个组件相关的文件。
3、在指定组件的文件夹中右键->新建Component创建组件。这样创建的目的是在json文件中添加"component": true,将其声明为一个组件。
下面开始例子:
1、组件页面 index.wxml
<!-- 通知框 -->
<view class="notify-view" style="margin-top: {{ windowHeight - (windowHeight * 0.3) }}px; width: {{ windowWidth }}px; display: {{ show ? 'flex' : 'none' }};">
<view class="notify-content-view">
<text class="notify-content-text">{{ message }}</text>
</view>
</view>
2、组件样式 index.wxss
/* components/notify/index.wxss */
.notify-view {
position: fixed;
z-index: 11;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.notify-content-view {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: rgba(0, 0, 0, 0.75);
padding: 15px;
border-radius: 8px;
}
.notify-content-text {
font-size: 14px;
font-family: PingFangSC-Regular, PingFang SC;
font-weight: 400;
color: #FFFFFF;
line-height: 20px;
}
3、组件json配置 index.json
{
"component": true,
"usingComponents": {}
}
4、组件页面的js index.js
// components/notify/index.js
Component({
options: {
/**
styleIsolation 选项从基础库版本 2.6.5 开始支持。它支持以下取值:
isolated 表示启用样式隔离,在自定义组件内外,使用 class 指定的样式将不会相互影响(一般情况下的默认值);
apply-shared 表示页面 wxss 样式将影响到自定义组件,但自定义组件 wxss 中指定的样式不会影响页面;
shared 表示页面 wxss 样式将影响到自定义组件,自定义组件 wxss 中指定的样式也会影响页面和其他设置了 apply-shared 或 shared 的自定义组件。(这个选项在插件中不可用。)
*/
styleIsolation: 'isolated'
},
/**
* 组件的属性列表
*/
properties: {
message: {
type: String,
value: ''
},
show: {
type: Boolean,
value: false,
},
},
/**
* 组件的初始数据
*/
data: {
windowWidth: 0,
windowHeight: 0,
},
/**
* 生命周期函数
*/
ready: function() {
var _this = this;
wx.getSystemInfo({
success: function(res) {
_this.setData({
windowWidth: res.windowWidth,
windowHeight: res.windowHeight,
});
}
});
},
/**
* 组件的方法列表
*/
methods: {
}
});
5、组件js notify.js
const defaultOptions = {
show: false,
message: '',
selector: '#cus-notify',
};
let currentOptions = Object.assign({}, defaultOptions);
function getContext() {
const pages = getCurrentPages();
return pages[pages.length - 1];
}
const Notify = (options) => {
options = Object.assign(Object.assign({}, currentOptions), options);
const context = options.context || getContext();
const notify = context.selectComponent(options.selector);
delete options.context;
delete options.selector;
if (notify) {
notify.setData(options);
wx.nextTick(() => {
notify.setData({ show: true });
});
//1.5秒后自动关闭
setTimeout(() => {
notify.setData({ show: false });
}, 1500);
}
else {
console.warn('未找到 cus-notify 节点,请确认 selector 及 context 是否正确');
}
};
Notify.show = (options) => Notify(options);
export default Notify;
6、使用方法
需要用到notify的页面引入notify组件:
{
"usingComponents": {
"cus-notify": "../../components/notify/index"
}
}
页面加入notify节点:
<cus-notify id="cus-notify"/>
在页面的js中弹出notify通知:
//引入notify组件
import Notify from '../../components/notify/notify';
//在代码中调用
Notify.show({
message: "测试呢",
selector: '#cus-notify',
});