我试图解决这个与 UI 动态变化相关的问题,首先尝试使用原生 vanilla JS,但进一步适应 Nuxt 3 和 Vue。不过,我在函数识别和使用计算属性的方法“setAttribute”方面遇到了问题。
当前脚本:
<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>
导演。层次结构:
当前错误行:
我尝试使用 vue 路由器、计算和 onMounted 的逻辑将 src 从“fire-hor.gif”更改为“bonfire.gif”(如果它是 /index 页面或 /banda 页面),但我对新的感到困惑Nuxt 语法。
我知道我是一个初学者,并且我的代码中也有一些逻辑错误。请指导我!
您将
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" />