两个浏览器窗口进行联动

两个浏览器窗口进行联动,可以使用Vue Router和Vuex来实现。具体步骤如下:

1.首先安装Vue Router和Vuex:

npm install --save vue-router vuex

2.在Vue项目中创建一个store.js文件,用于存储全局状态:

import Vue from 'vue' 
import Vuex from 'vuex' 
Vue.use(Vuex) 
export default new Vuex.Store({ 
    state: {
        windowWidth: window.innerWidth,
        windowHeight: window.innerHeight
        },
    mutations: { 
        setWindowWidth(state, width) { 
            state.windowWidth = width 
        }, 
        setWindowHeight(state, height) {
            state.windowHeight = height 
        } 
     },
     actions: {
         updateWindowWidth({ commit }) {
             commit('setWindowWidth', window.innerWidth)
        }, 
        updateWindowHeight({ commit }) { 
            commit('setWindowHeight', window.innerHeight) 
        }
     } 
})

3.在Vue项目中创建一个router.js文件,用于配置路由:

<template>
  <div :style="{ height: windowHeight + 'px' }">
    <h1>Home</h1>
    <p>Window width: {{ windowWidth }}</p>
    <p>Window height: {{ windowHeight }}</p>
  </div>
</template>

<script>
export default {
  name: 'Home',
  computed: {
    windowWidth() {
      return this.$store.state.windowWidth
    },
    windowHeight() {
      return this.$store.state.windowHeight
    }
  }
}
</script>

4.在Vue项目中的App.vue文件中添加以下代码,用于监听窗口变化并更新全局状态:

export default {
  name: 'App',
  created() {
    window.addEventListener('resize', this.handleResize)
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    handleResize() {
      this.$store.dispatch('updateWindowWidth')
      this.$store.dispatch('updateWindowHeight')
    }
  }
}

5.在Vue项目中的Home.vue和About.vue组件中使用计算属性来获取全局状态,并根据状态来更新组件中的样式:

<template>
  <div :style="{ height: windowHeight + 'px' }">
    <h1>Home</h1>
    <p>Window width: {{ windowWidth }}</p>
    <p>Window height: {{ windowHeight }}</p>
  </div>
</template>

<script>
export default {
  name: 'Home',
  computed: {
    windowWidth() {
      return this.$store.state.windowWidth
    },
    windowHeight() {
      return this.$store.state.windowHeight
    }
  }
}
</script>
<template>
  <div :style="{ height: windowHeight + 'px' }">
    <h1>About</h1>
    <p>Window width: {{ windowWidth }}</p>
    <p>Window height: {{ windowHeight }}</p>
  </div>
</template>

<script>
export default {
  name: 'About',
  computed: {
    windowWidth() {
      return this.$store.state.windowWidth
    },
    windowHeight() {
      return this.$store.state.windowHeight
    }
  }
}
</script>

接着测试

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值