如何不修改变量名,在Vue模板的:class中访问computed属性song?
问题
你在Vue 3的<script setup>组件里定义了名为song的计算属性,但模板v-for循环的循环变量也用了song这个名字。现在要在循环项的:class绑定里访问外层的计算属性song,还不能改任何现有变量的名称,该怎么办?
相关代码
组件代码
<script lang="ts" setup> const songStore = useSongStore() // Pinia仓库 const song = computed(() => songStore.getCurrentSong.value); // 外层的计算属性song </script> <template> <!-- songStore.songList是ref类型 --> <li v-for="(song,song_idx) in songStore.songList" :key="song.id" :class="{'current-play' : song.id === /* 这里要访问外层的song */}" > </li> </template>
Pinia仓库代码(SongStore.ts)
// SongStore.ts export const useSongStore = defineStore('songStore', () => { const songList = ref<Array<Song>>([ { id: '1', singerId: '', title: '', album: '', picture: '', lyric: '', url: '' } ]); let currentSongIdx = ref(0); let currentSong = ref<Song>(songList.value[currentSongIdx.value]); const getCurrentSong = computed(() => { setCurrentSong(songList.value[currentSongIdx.value]); return currentSong; }); const setCurrentSong = (song: Song) => { currentSong.value = song; } return {songList ,currentSongIdx ,currentSong,getCurrentSong,setCurrentSong } })
解决办法
v-for的循环变量会在当前<li>的作用域里覆盖外层的同名song,你可以给外层的song套个容器对象,不用改任何现有变量名:
- 在组件的
<script setup>里加一个容器对象,把song挂进去:
const songStore = useSongStore() const song = computed(() => songStore.getCurrentSong.value); // 新增这个容器,原song变量名不动 const outer = { song };
- 然后在模板的
:class绑定里,通过这个容器访问外层的song:
<li v-for="(song,song_idx) in songStore.songList" :key="song.id" :class="{'current-play' : song.id === outer.song.id}" > </li>
这样既保留了所有变量的原名,又能正确拿到外层的计算属性song,解决了作用域冲突的问题。
另外提个小建议:你Pinia仓库里的getCurrentSong计算属性有问题——计算属性不该包含副作用(比如调用setCurrentSong修改状态),这不符合计算属性“纯函数”的设计逻辑,容易引发奇怪的状态更新问题,建议把这部分逻辑移到setCurrentSong或者其他方法里。
内容的提问来源于stack exchange,提问作者steelhead
相关产品推荐
相关产品推荐

