中文 | English
iframe和window间同步状态的解决方案
Your star is the greatest encouragement to me.
- 多个iframe和window间的双向状态同步
- iframe触发load事件时自动从父对象初始化状态
- 允许配置个性化的同步行为
注意 window.postMessage对传送的数据有限制, 类似于JSON.parse()和JSON.stringfy()。若你遇到相关问题,可尝试给broadcast和transfer配置convert函数。
<script src="https://cdn.jsdelivr.net/npm/vuex-iframe-sync/dist/vuex-iframe-sync.umd.js"></script>
npm install vuex-iframe-sync --save
yarn add vuex-iframe-sync
// 父对象的组件
<iframe id="frameId1"/>
<iframe id="frameId2"/>
// 父对象的store配置
import {broadcast} from 'vuex-iframe-sync'
export default new Vuex.store({
// ...
plugins: [
broadcast('frameId1,frameId2')
]
})
// iframe的store配置
import {transfer} from 'vuex-iframe-sync'
export default new Vuex.store({
// 与父对象相同的state和mutations配置
plugins: [
transfer()
]
})
当父对象状态变更时,通过postMessage API传递给各个iframe。
ids <String|Array>
: 以逗号分隔的iframeId或形如[{id: iframeId, origin: iframeOrigin}...]的数组
options
: 下列属性用于配置父对象的个性化同步行为:
convert <Function(payload)>
: 在传递给各个iframe前转换数据
当iframe自身状态变更时,通过postMessage API传递给父对象
options
: 下列属性用于配置iframe的个性化同步行为:
convert <Function(payload)>
: 在传递给父对象前转换数据created <Function(id, store, send)>
: 在iframe load事件后调用(id: iframe的id,store:自身的store,send<Function(type, payload)>:相当于parent.$store.commit,触发父对象中mutations)destroyed <Function(id, store, send)>
: 在iframe beforeunload事件后调用(id: iframe的id,store:自身的store,send<Function(type, payload)>:相当于parent.$store.commit,触发父对象中mutations)
# serve with with-webpack example at localhost:8080
npm run dev
# serve with simple example at localhost:8080
npm run dev:simple
# test with jest
npm run test
# build for production with minification
npm run build
# build for production with live example
npm run build:docs
- 欢迎建议