国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【VUE】localStorage、indexedDB跨域數(shù)據(jù)操作實(shí)戰(zhàn)筆記

這篇具有很好參考價(jià)值的文章主要介紹了【VUE】localStorage、indexedDB跨域數(shù)據(jù)操作實(shí)戰(zhàn)筆記。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

由于業(yè)務(wù)需求,最近研究localStorage、indexedDB等如何跨域進(jìn)行CRUD管理,經(jīng)過(guò)一番研究,封裝了如下代碼并做個(gè)筆記

環(huán)境

  • vue: ^3.3.4

實(shí)戰(zhàn)

發(fā)送端(即觸發(fā)站點(diǎn))

App.vue中引入CrossDomainStorage組件(后面有實(shí)現(xiàn)過(guò)程)

<script setup>
import { ref } from 'vue'
import CrossDomainStorage from "@/components/CrossDomainStorage/index.vue";
const crossDomainStorageRef = ref(null)

function sendTest() {
  if (crossDomainStorageRef.value){
    crossDomainStorageRef.value.sendMessage("getItem", {key:'APP_THEME_SCREEN'})
  }
}
</script>

<template>
  <div>
    <button @click="sendTest">測(cè)試</button>
    <CrossDomainStorage :src="'http://xxxx.xxx/'" ref="crossDomainStorageRef"/>
  </div>
</template>

接收端(即目標(biāo)站點(diǎn))

為了方便直接在App.vue中實(shí)踐文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-632852.html

<script setup>
import ParentMsgListener from '@/utils/parentMsgListener'

const parentMsgListener = new ParentMsgListener()
parentMsgListener.addPermissionModule({ // 設(shè)置權(quán)限key對(duì)應(yīng)處理方法
	localStorage: {
		setItem: localStorage.setItem,
		getItem: localStorage.getItem,
	},
	asyncTest: {
		text: async ()=> await 'asyncValue',
		text2: () => 'testValue',
	}
});
parentMsgListener.addPermission([ // 設(shè)置可操作的對(duì)象列表
	'localStorage'
])
parentMsgListener.start();
</script>

實(shí)現(xiàn)代碼

CrossDomainStorage組件

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';

defineOptions({
  name: 'CrossDomainStorage'
});

const iframeRef = ref();
const emit = defineEmits(['onLoad','response'])
const props = defineProps({
  src: {type: String, default:()=>"", required:true}
});
const status = ref(false)
const iframeStyles = reactive({
  position: 'fixed',
  top:0,
  left:0,
  width: 0,
  height: 0,
  zIndex:-1
});

window.addEventListener('message', function (e) {
  if (e.data && e.data.request){
    console.log('[發(fā)送端]從iframe獲取數(shù)據(jù)', e.data)
    emit('response', e.data||null)
  }
});

function sendMessage(method: string, param: object, key: string) {
  if (status.value===false)return;
  key = key?key:'localStorage'
  if (iframeRef?.value){
    const iframeNode = iframeRef.value.contentWindow;
    let request = {key, method, param}
    console.log('[發(fā)送端]向iframe發(fā)送request:', request)
    setTimeout(function () {
      iframeNode.postMessage(request, '*')
    }, 500)
  }
}

defineExpose({
  sendMessage: (method: string, param: object, key: string)=>sendMessage(method, param, key)
})

onMounted(()=>{
  if (!!iframeRef.value && !!iframeRef.value.contentWindow){
    iframeRef.value.onload = function () {
      status.value = true;
      emit('onLoad', true)
    }
  }
})
</script>

<template>
  <iframe ref="iframeRef" :src="props.src"
          :style="iframeStyles"
          frameborder="0"
          scrolling="no"/>
</template>

parentMsgListener.ts封裝消息管理類

// src/utils/parentMsgListener.ts
const messageLog = function (log, ...arg){
    arg.unshift(`[接收端]`, log)
    console.log.apply(console, arg)
}

interface permissionOptions {
    key: string[],
    module: object
}

/**
 * 監(jiān)聽(tīng)響應(yīng)攔截
 *
 * @param {object}   e          接收數(shù)據(jù)
 * @param {array}   permission 權(quán)限列表
 * @param {function} response   接收回調(diào)
 *
 * @return {void}
 */
const listenerResponse = async function (e, permission: permissionOptions, response) {
    if (e.data && !!e.data.key && permission.key.includes(e.data.key)){
        let result = undefined;
        let lib = permission.module[e.data.key] || undefined;
        let method = e.data?.method || '';
        let param  = e.data?.param||{};
        if (!!lib){
            let _param = [];
            for (let key in param){
                _param.push(`'${param[key]}'`)
            }
            try { // 調(diào)用非js內(nèi)置方法且兼容異步調(diào)用處理方法
                result = await ((lib[method]).apply(lib[method], Object.values(param)));
            }catch (error) { // 調(diào)用js內(nèi)置方法
                result = eval(`${e.data.key}.${method}(${_param.join(',')})`);
            }
        }
        messageLog('response:', result)
        response({
            request: e.data,
            response: result
        }, '*')
    }
}

class ParentMsgListener {

    /**
     * 消息調(diào)用權(quán)限對(duì)應(yīng)處理
     * @var {object}
     */
    private permissionMap = {};

    /**
     * 消息允許調(diào)用權(quán)限
     * @var {string[]}
     */
    private permission = []

    constructor(permission) {
        if (permission && permission.length>0){
            this.addPermission(permission)
        }
    }

    /**
     * 添加授權(quán)權(quán)限key對(duì)應(yīng)處理模塊
     *
     * @param {string|object} name 權(quán)限key
     * @param {function} fn 權(quán)限key處理方法
     *
     * @return this
     */
    addPermissionModule(name:string|object, fn){
        if (!fn && typeof name === 'object'){ // 批量導(dǎo)入
            for (let moduleKey in name){
                this.addPermissionModule.call(this, moduleKey, name[moduleKey]);
            }
        }else if(typeof name === 'string' && !!fn) { // 逐個(gè)導(dǎo)入
            this.permissionMap[name] = fn;
        }
        return this;
    }

    /**
     * 添加授權(quán)權(quán)限
     *
     * @param {string|string[]} permissionKey 權(quán)限key
     *
     * @return this
     */
    addPermission(permissionKey: string|string[]){
        if (permissionKey instanceof Array){
            let that = this;
            permissionKey.forEach((key)=>{
                that.permission.push(key)
            })
        }else{
            this.permission.push(permissionKey)
        }
        return this;
    }

    /**
     * 發(fā)送消息
     *
     * @param {object} message      發(fā)送內(nèi)容
     * @param {string} targetOrigin 默認(rèn):*
     *
     * @return {void}
     */
    sendMessage(message:any, targetOrigin:string = '*'){
        messageLog('發(fā)送消息', message)
        window.parent.postMessage(message, targetOrigin)
    }

    /**
     * 啟動(dòng)監(jiān)聽(tīng)
     */
    start(){
        window.addEventListener(
            'message',
            (e)=>listenerResponse(e, {
                key: this.permission,
                module: this.permissionMap
            }, this.sendMessage)
        )
    }
}

export default ParentMsgListener

到了這里,關(guān)于【VUE】localStorage、indexedDB跨域數(shù)據(jù)操作實(shí)戰(zhàn)筆記的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 【SpringBoot+Vue】全網(wǎng)最簡(jiǎn)單但實(shí)用的前后端分離項(xiàng)目實(shí)戰(zhàn)筆記 - 數(shù)據(jù)庫(kù)設(shè)計(jì)

    配套視頻地址:https://www.bilibili.com/video/BV1dG4y1T7yp/ 如果您需要原版筆記,請(qǐng)up喝口水,可以上我的淘寶小店 青菜開(kāi)發(fā)資料 購(gòu)買,或點(diǎn)擊下方鏈接直接購(gòu)買: 源碼+PDF版本筆記 源碼+原始MD版本筆記 感謝支持!

    2024年02月16日
    瀏覽(24)
  • Vue中如何進(jìn)行本地存儲(chǔ)(LocalStorage)

    Vue中如何進(jìn)行本地存儲(chǔ)(LocalStorage)

    在Vue.js應(yīng)用程序中,本地存儲(chǔ)(LocalStorage)是一個(gè)強(qiáng)大的工具,用于在瀏覽器中保存和檢索數(shù)據(jù)。它允許您在不使用服務(wù)器或后端數(shù)據(jù)庫(kù)的情況下,在用戶的瀏覽器中存儲(chǔ)數(shù)據(jù),以實(shí)現(xiàn)數(shù)據(jù)的持久性。本地存儲(chǔ)對(duì)于保存用戶首選項(xiàng)、用戶身份驗(yàn)證令牌、購(gòu)物車數(shù)據(jù)等場(chǎng)景都非

    2024年02月07日
    瀏覽(24)
  • Vue3優(yōu)雅地監(jiān)聽(tīng)localStorage變化

    Vue3優(yōu)雅地監(jiān)聽(tīng)localStorage變化

    目錄 ??前言? ?? 為什么要這樣做? ?? 思路 ?? 實(shí)現(xiàn) ?? 實(shí)現(xiàn)中介者模式 ?? 重寫localStorage ?? 實(shí)現(xiàn)useStorage hook ?? 測(cè)試 ?? 使用localStorage ?? 監(jiān)聽(tīng)localStorage變化 ?? 結(jié)果 ????????最近在研究框架,也仔細(xì)用了Vue3一些功能,今天分享一次我的實(shí)踐: ????????原生的

    2024年02月08日
    瀏覽(24)
  • token + localstorage 驗(yàn)證登錄(vue)詳細(xì)教程

    token + localstorage 驗(yàn)證登錄(vue)詳細(xì)教程

    token : 本質(zhì)是驗(yàn)證身份的令牌,一般由用戶通過(guò)賬戶密碼登錄后,服務(wù)端把這些憑證通過(guò)加密等一些列操作后得到的字符串。 token 登錄流程: 客戶端用賬戶密碼請(qǐng)求登錄; 服務(wù)端接收請(qǐng)求,驗(yàn)證賬戶密碼; 驗(yàn)證成功后,服務(wù)端發(fā)送token給客戶端; 客戶端接收到token后保存,

    2023年04月21日
    瀏覽(14)
  • 【Vue】瀏覽器緩存sessionStorage、localStorage、Cookie

    【Vue】瀏覽器緩存sessionStorage、localStorage、Cookie

    目錄 一、sessionStorage 1、簡(jiǎn)介 2、方法 3、代碼示例 a、存取單個(gè)數(shù)據(jù) b、存取對(duì)象 c、清除數(shù)據(jù) 二、localStorage 1、簡(jiǎn)介 2、方法 3、代碼示例 三、cookie 1、簡(jiǎn)介 2、方法 3、代碼示例 四、三者區(qū)別 1、sessionStorage與localStorage區(qū)別 2、sessionStorage、localStorage、cookie區(qū)別 五、往期相關(guān)優(yōu)

    2024年02月07日
    瀏覽(31)
  • 在Vue 3中使用useStorage輕松實(shí)現(xiàn)localStorage功能

    VueUse 介紹 VueUse文檔:Get Started | VueUse VueUse是基于Vue3的Composition API的實(shí)用函數(shù)的集合, useStorage 是其中的一個(gè)函數(shù)。我們可以使用 useStorage 來(lái)實(shí)現(xiàn)我們的 localStorage 功能。 安裝 使用CDN useStorage() 的用法 useStorage () 將要用于引用的鍵名作為第一個(gè)參數(shù)傳遞,將要保存的值作為第

    2024年02月05日
    瀏覽(18)
  • Vue中如何進(jìn)行狀態(tài)持久化(LocalStorage、SessionStorage)

    Vue中如何進(jìn)行狀態(tài)持久化(LocalStorage、SessionStorage)

    在Vue應(yīng)用中,通常需要將一些狀態(tài)進(jìn)行持久化,以便在用戶關(guān)閉瀏覽器或刷新頁(yè)面后,仍能保留之前的狀態(tài)。常見(jiàn)的持久化方式包括 LocalStorage 和 SessionStorage 。本文將介紹如何使用這兩種方式來(lái)實(shí)現(xiàn)狀態(tài)的持久化。 LocalStorage 是HTML5中引入的一種持久化方式,它可以將數(shù)據(jù)存儲(chǔ)

    2024年02月09日
    瀏覽(22)
  • Vue——vuex使用、Router使用、localstorage、sessionstorage和cookie
  • VUE項(xiàng)目使用axios發(fā)送post跨域請(qǐng)求,返回?cái)?shù)據(jù)失敗問(wèn)題

    Access to XMLHttpRequest at \\\'http://xxxx\\\' from origin \\\'http://localhost:8080\\\' has been blocked by CORS policy: Response to preflight request doesn\\\'t pass access control check: No \\\'Access-Control-Allow-Origin\\\' header is present on the requested resource. 第一步 ,在后端接受方,對(duì)返回的數(shù)據(jù)添加 響應(yīng)頭 ,使用下面這句代碼: 第二步

    2024年02月11日
    瀏覽(26)
  • node+vue開(kāi)發(fā)環(huán)境下接口數(shù)據(jù)傳遞中的跨域問(wèn)題

    大部分瀏覽器自帶的保護(hù)措施,限制用戶在一個(gè)域名下請(qǐng)求另一個(gè)域名的數(shù)據(jù) 跨域?qū)τ谇昂蠖碎_(kāi)發(fā)者來(lái)說(shuō),就像一塊狗皮膏藥,無(wú)論是面試還是開(kāi)發(fā)中,都會(huì)經(jīng)常遇到。 之所以出現(xiàn)跨域問(wèn)題,是因?yàn)闉g覽器的同源策略,為了隔離潛在的惡意文件,為了防御來(lái)自歪門邪道的攻

    2024年01月24日
    瀏覽(28)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包