vue中iframe的src重复刷新

在Vue中使用iframe时,可以使用Vue实例的生命周期钩子函数,在组件中监听数据变化并适时地刷新iframe的src。

例如,你可以在组件的watch选项中监听某个数据的变化,并在变化时动态更新iframe的src:

<template>
    <iframe :src="url"></iframe>
  </div>
</template>
<script>
export default {
  data () {
    return {
      url: ''
  watch: {
    url: function (newVal) {
      this.$nextTick(() => {
        this.$refs.iframe.src = newVal
</script>

另一种方法是在组件的mounted钩子函数中使用MutationObserver监听iframe的src属性,如果发生变化,就重新刷新iframe:

<template>
    <iframe ref="iframe" :src="url"></iframe>
  </div>
</template>
<script>
export default {
  data () {
    return {
      url: ''
  mounted () {
    this.observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.attributeName === 'src') {
          this.$refs.iframe.src = this.url
    this.observer.observe(this.$refs.iframe, { attributes: true })
  beforeDestroy () {
    this.observer.disconnect()
</script>

这两种方法都可以实现在Vue中对iframe的src进行重复刷新。

  •