vue3+setup中监听路由变化改变样式

在Vue 3中,有一个非常方便的API可以观察响应式数据的变化,即watchEffect。watchEffect是一个新的API,可以自动跟踪响应式数据的变化,并在其发生变化时执行回调函数。这意味着您不需要手动指定依赖项,watchEffect可以根据您的代码自动推断依赖项。

在本例中,我们将使用watchEffect和useRoute来观察路由的变化,并更新页面的样式。下面是代码实现:

<template>
  <div class="container">
    <headerVue style="z-index: 2"></headerVue>
    <div class="aside">
      <menuVue style="z-index: 3"></menuVue>

      <!--1.为需要改变样式的标签设置:style="style"-->
      <div class="box" :style="style">
        <!-- 面包屑导航 -->
        <BreadCrumb />
        <router-view class="subPage" style="z-index: 1"></router-view>
      </div>
    </div>
  </div>
</template>

<script setup>
import headerVue from "../components/header.vue";
import menuVue from "../components/menu.vue";
import "../style/base.scss";
import "../style/subPage.scss";

<!--2.导入所需-->
import { useRoute } from 'vue'
import { reactive, watchEffect } from 'vue'

<!--3.定义样式变量-->
const style = reactive({
  background: '#eff1f7'
})

<!--4.创建route的实例-->
const route = useRoute()

<!--5.监听路由,改变样式-->
watchEffect(() => {
  if (route.path === '/dataScreen') {
    style.background = '#f0f0f0'
  } else {
    style.background = '#ffffff'
  }
})

</script>

<style lang="scss" scoped>
.box {
  position: relative;
  padding: 30px;
  height: 900px;
  // background-color: #eff1f7;
}
.container {
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.aside {
  display: flex;
  flex-direction: row;
}
.subPage {
  width: 100%;
  height: 100%;
}
</style>

在这个例子中,我们定义了一个响应式的style对象,并使用useRoute来获取当前的路由信息。然后,我们使用watchEffect来观察route.path的变化,并在回调函数中更新style对象。如果当前路由为'/dataScreen',则我们将样式更改为蓝灰色(#eff1f7)背景,否则为白色背景。

总之,使用watchEffect可以非常方便地观察响应式数据的变化,并执行相关的操作。如果您需要在Vue 3中观察数据的变化,不妨尝试使用watchEffect。

实现效果:

dataScreen页面

其他 

猜你喜欢

转载自blog.csdn.net/m0_62742402/article/details/129572292