如何使用 Vue 3 和 Nuxt 根据加载的当前页面将计算图像 SRC 属性更改为另一属性?

问题描述 投票:0回答:1

我试图解决这个与 UI 动态变化相关的问题,首先尝试使用原生 vanilla JS,但进一步适应 Nuxt 3 和 Vue。不过,我在函数识别和使用计算属性的方法“setAttribute”方面遇到了问题。

如何使图像的 SRC 成为计算属性,然后根据我当前的“route.path”更改它?我正在努力适应现代语法。

当前脚本:

<script setup>
import { ref, onMounted } from 'vue';
import {reactive, computed} from 'vue';
import { useRoute } from 'vue-router';

const route = useRoute();
const imagem = ref();


onMounted(() => {
    changeImg();
    
})
const properties = reactive({
    home: "~/assets/img/fire-hor.gif",
    alt: "Logo do Barnabé",
    banda: "~/assets/img/bonfire.gif",
    
})

const enhangeImg = computed(() => {
    function changeImg(){

        var PAGINA = route.path;
        if (typeof route.path !== "undefined") {
            if (PAGINA === '/') {
                imagem.setAttribute('src', properties.home);
            }
            else if (PAGINA === '/banda') {
                imagem.setAttribute('src', properties.banda);
            }
        return changeImg();
        }
    }
    return enhangeImg = changeImg(); 
})

</script>

当前模板:

<template >
    <div class="barna-logo">
        <img ref="imagem"  id="image" 
        :src="(enhangeImg)" :alt="(properties.alt)" />
    </div>
</template>

导演。层次结构:

directory

当前错误行:

error + console

我尝试使用 vue 路由器、计算和 onMounted 的逻辑将 src 从“fire-hor.gif”更改为“bonfire.gif”(如果它是 /index 页面或 /banda 页面),但我对新的感到困惑Nuxt 语法。

我知道我是一个初学者,并且我的代码中也有一些逻辑错误。请指导我!

vue.js vuejs3 nuxt.js vuetify.js nuxtjs3
1个回答
0
投票

您将

computed
值与
function
混淆了。计算方法的返回是一个
Proxy
对象,它为您提供一个
value
属性,其中包含计算的结果值。

您想要的是观察 Nuxt 3 中

route
的变化,然后做出相应的响应:

const properties = reactive({
    home: "~/assets/img/fire-hor.gif",
    alt: "Logo do Barnabé",
    banda: "~/assets/img/bonfire.gif",
    
})
const imageSrc = ref(properties.home);
const route = useRoute();

watch(route, (routeChange) => {
    const path = routeChange.path;

    if (PAGINA === '/') {
        imageSrc.value = properties.home;
    }

    if (PAGINA === '/banda') {
        imageSrc.value = properties.banda
    }
}, {deep: true, immediate: true})

当然,将

imageSrc
的值绑定到您的
<img
元素:

<img :src="imageSrc" :alt="properties.alt" />
© www.soinside.com 2019 - 2024. All rights reserved.