vue-sync修饰符解析以及切换iframe页面进行保存提示功能的思路
Sync修饰符
在 Vue 2.x 中,v-model 的 .sync 修饰符允许子组件更新一个 prop 的值,并通知父组件重新渲染。这在父子组件通信中非常有用。
父组件:
<template><div><child-component :title.sync="parentTitle"></child-component></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {components: {ChildComponent},data() {return {parentTitle: '初始标题'};}
}
</script>
子组件:
<template><button @click="updateTitle">更新标题</button>
</template><script>
export default {props: ['title'],methods: {updateTitle() {this.$emit('update:title', '新标题');}}
}
</script>
在这个例子中,当子组件的按钮被点击时,它会发出一个 update:title 事件,并传递一个新的标题。父组件监听这个事件并更新其 parentTitle 数据属性。这样,你就实现了数据的双向绑定。
iframe切换前提示保存功能的实现思路
实现思路:
主页面与iframe页面进行通信。
在切换其他菜单时,主页面向iframe页面发送switchTab的消息,如果iframe页面返回消息noSwitchTab,那么主页面的切换菜单函数不执行,进行缓存。如果iframe页面需要继续之前的中断的切换逻辑,那么发送restoreSwitchTab消息给主页面,那么主页面继续之前的切换菜单的函数。
点击切换菜单组件代码:
onMenuSelect(name){let vm = this;window.global.postSaveMsg(this.onMenuSelectCallback.bind(vm),name)},
主页面代码:
data:{isSwitchTab:true,lastSwitchTabInfo:{},},window.addEventListener('message', e => {let config = e.data;if(e.data.noSwitchTab){vm.isSwitchTab = false;}if(e.data.restoreSwitchTab){vm.isSwitchTab = true;if(vm.lastSwitchTabInfo && vm.lastSwitchTabInfo.func){vm.lastSwitchTabInfo.func(vm.lastSwitchTabInfo.args);vm.lastSwitchTabInfo = {};}}},postSaveMsg(func,args){let vm = this;window.global.isSwitchTab = true;window.global.lastSwitchTabInfo = {};vm.postMessage();setTimeout(() => {if (window.global.isSwitchTab) {func(args);}else{window.global.lastSwitchTabInfo = {func:func,args:args};}}, 200);},postMessage(){let dom = document.getElementById('centerContentIframe') if(dom && dom.children && dom.children.length){document.getElementById('centerContentIframe').children[0].contentWindow.postMessage({type:"switchTab",id: 'centerContentIframe',switchTab: true});}},
iframe页面代码
mounted(){let vm =this;window.addEventListener("message", function (e) {const postData = {noSwitchTab:true};window.parent.postMessage(postData,"*");let config = {title: "当前内容未保存,是否保存?",width:'440',onOk: () => {},onCancel:()=>{const postData = {restoreSwitchTab:true};window.parent.postMessage(postData,"*");}};vm.$Modal.confirm(config);});},