🔧 阿川の電商水電行
Shopify 顧問、維護與客製化
💡
小任務 / 單次支援方案
單次處理 Shopify 修正/微調
⭐️
維護方案
每月 Shopify 技術支援 + 小修改 + 諮詢
🚀
專案建置
Shopify 功能導入、培訓 + 分階段交付

例如有個 component 如下:

<template>
    <iframe :src="url.src"></iframe>
</template>

<script>
export default {
    data() {
        return {
            url: {
                src: 'https://example.com',
            },
        };
    },
};
</script>

這時如果 src 網址變動,iframe 內會顯示新的網頁,同時也會造成 browser history 被修改,也就是點擊瀏覽器的上一頁時,會發現整個網頁沒有跳回上一頁,而是 iframe 回復到舊的網址,但如果這不是你想要的效果呢?

vue.js 官方文件介紹 key 的時候提到:

It can also be used to force replacement of an element/component instead of reusing it.

所以答案就是在 iframe 加上動態的 key,key 和 src 同時變動時,vue.js 就會強制替換成新的 iframe,跳過 browser history 被修改的問題,點擊瀏覽器的上一頁就能正常回到前一頁了,範例如下:

<template>
    <iframe :key="url.key" :src="url.src"></iframe>
</template>

<script>
export default {
    data() {
        return {
            url: {
                key: 1,
                src: 'https://example.com',
            },
        };
    },
};
</script>

P.S. 參考資料中,文章作者提到 react 也是一樣的處理方式。

參考資料:
https://vuejs.org/api/built-in-special-attributes.html
https://www.aleksandrhovhannisyan.com/blog/react-iframes-back-navigation-bug/
https://stackoverflow.com/questions/821359/reload-an-iframe-without-adding-to-the-history#answer-77278956


此人尚未填寫簡介。
按讚的人:

共有 0 則留言


此人尚未填寫簡介。
🏆 本月排行榜
🥇
站長阿川
📝21   💬9   ❤️4
665
🥈
我愛JS
📝4   💬13   ❤️7
257
🥉
御魂
💬1  
3
#4
2
#5
Jack
1
評分標準:發文×10 + 留言×3 + 獲讚×5 + 點讚×1 + 瀏覽數÷10
本數據每小時更新一次
🔧 阿川の電商水電行
Shopify 顧問、維護與客製化
💡
小任務 / 單次支援方案
單次處理 Shopify 修正/微調
⭐️
維護方案
每月 Shopify 技術支援 + 小修改 + 諮詢
🚀
專案建置
Shopify 功能導入、培訓 + 分階段交付