例如有個 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 則留言