Vue.js响应式API使用及下拉菜单切换失效问题解决
问题修复方案
核心问题及修复步骤:
- ref变量修改方式错误
Vue 3中通过ref()创建的响应式变量,必须通过.value属性修改值,直接赋值会破坏其响应式特性。原代码中showDropDown = !showDropDown是错误写法,需改为:
showDropDown.value = !showDropDown.value;
- 变量名不匹配+未做响应式处理
脚本里定义的变量是currentView,但模板中使用的是currentComponent,且该变量未用ref包裹,导致视图切换逻辑无效。修正后:
const currentComponent = ref("MainPage")
- 静态资源路径错误
Vue项目打包后src目录会被移除,原路径./src/assets/xxx无法正确访问资源,需改为项目根路径相对写法或别名@(指向src目录):
const imgSrcProfile = "@/assets/defaultUserIcon.webp" const imgSrcLogo = "@/assets/DailyQuotes_Logo.png"
- 视图切换未使用动态组件
直接写<MainPage/>无法根据变量切换视图,需使用Vue动态组件语法:
<component :is="currentComponent"/>
修复后的完整代码:
<script setup> import MainPage from './components/MainPage.vue' import ProfilePage from './components/ProfilePage.vue' import FriendsPage from './components/FriendsPage.vue' import SettingsPage from './components/SettingsPage.vue' import SignOutPage from './components/SignOutPage.vue' const currentComponent = ref("MainPage") const showDropDown = ref(false) const imgSrcProfile = "@/assets/defaultUserIcon.webp" const imgSrcLogo = "@/assets/DailyQuotes_Logo.png" function toggleDropDown (){ console.log("test"); showDropDown.value = !showDropDown.value; } </script> <template> <main> <header> <div class="logo"> <img @click="currentComponent='MainPage'" :src="imgSrcLogo"> </div> <div class="profile"> <img @click="toggleDropDown" :src="imgSrcProfile"> <div id="dropDownMenu" v-if="showDropDown"> <a @click="currentComponent = 'ProfilePage'">Profile</a> <a @click="currentComponent = 'FriendsPage'">Friends</a> <a @click="currentComponent = 'SettingsPage'">Settings</a> <a @click="currentComponent = 'SignOutPage'">Sign out</a> </div> </div> </header> <component :is="currentComponent"/> </main> </template>
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

