Westore 开源两天就突破了 1000 star,还登顶过Github日榜第一名。期间受到了海量关注,收到了大量的中肯和实用的反馈和意见。小程序插件开发的诉求是非常重要的意见之一。所以我马不停蹄地努力连夜更新,看 Github 提交记录就知道我凌晨 3 点钟有合并 PR,也有提交代码 = =! Github地址: github.com/dntzhang/we… 先回顾一下小程序现有的痛点:
所以没使用 westore 的时候经常可以看到这样的代码: 使用 Westore 对编程体验的改善: 上面两种方式也可以混合使用。 这里需要特别强调,虽然 this.update 可以兼容小程序的 this.setData 的方式传参,但是更加智能,this.update 会按需 Diff 或者 透传给 setData。原理: 再举个例子: this.store.data.motto = 'Hello Store222'
this.store.data.b.arr.push({ name: 'ccc' })
this.update()
复制代码
等同于 this.update({
motto:'Hello Store222',
[`b.arr[${this.store.data.b.arr.length}]`]:{name:'ccc'}
})
复制代码
小程序插件小程序插件是对一组 js 接口、自定义组件或页面的封装,用于嵌入到小程序中使用。插件不能独立运行,必须嵌入在其他小程序中才能被用户使用;而第三方小程序在使用插件时,也无法看到插件的代码。因此,插件适合用来封装自己的功能或服务,提供给第三方小程序进行展示和使用。 插件开发者可以像开发小程序一样编写一个插件并上传代码,在插件发布之后,其他小程序方可调用。小程序平台会托管插件代码,其他小程序调用时,上传的插件代码会随小程序一起下载运行。 插件开发Westore 提供的目录如下:
|--components
|--westore
|--plugin.json
|--store.js
复制代码
创建插件: import create from '../../westore/create-plugin'
import store from '../../store'
//最外层容器节点需要传入 store,其他组件不传 store
create(store, {
properties:{
authKey:{
type: String,
value: ''
}
},
data: { list: [] },
attached: function () {
// 可以得到插件上声明传递过来的属性值
console.log(this.properties.authKey)
// 监听所有变化
this.store.onChange = (detail) => {
this.triggerEvent('listChange', detail)
}
// 可以在这里发起网络请求获取插件的数据
this.store.data.list = [{
name: '电视',
price: 1000
}, {
name: '电脑',
price: 4000
}, {
name: '手机',
price: 3000
}]
this.update()
//同样也直接和兼容 setData 语法
this.update(
{ 'list[2].price': 100000 }
)
}
})
复制代码
在你的小程序中使用组件: <list auth-key="{{authKey}}" bind:listChange="onListChange" /> 复制代码
这里来梳理下小程序自定义组件插件怎么和使用它的小程序通讯:
这么方便简洁还不赶紧试试 Westore插件开发模板 ! 特别强调插件内所有组件公用的 store 和插件外小程序的 store 是相互隔离的。 原理页面生命周期函数
组件生命周期函数
由于开发插件时候的组件没有 this.page,所以 store 是从根组件注入,而且可以在 attached 提前注入:
export default function create(store, option) {
let opt = store
if (option) {
opt = option
originData = JSON.parse(JSON.stringify(store.data))
globalStore = store
globalStore.instances = []
create.store = globalStore
}
const attached = opt.attached
opt.attached = function () {
this.store = globalStore
this.store.data = Object.assign(globalStore.data, opt.data)
this.setData.call(this, this.store.data)
globalStore.instances.push(this)
rewriteUpdate(this)
attached && attached.call(this)
}
Component(opt)
}
复制代码
|
温馨提示:这篇文章没有解决您的问题?欢迎添加微信:18948083295,有微信小程序专业人员,保证有问必答。转载本站文章请注明转自http://www.okeydown.com/(微信小程序网)。
- 微信扫描二维码关注官方微信
- ▲长按图片识别二维码