Vue 修改和使用全局变量
在如下路径中新建index.js用于存储全局变量:index.js代码如下,这里定义了两个变量,playlist和playCurrentIndex,import { createStore } from 'vuex'export default createStore({state: {playlist:[{al:{},}],playCurrentIndex:0,},getters: {},mut
·
在如下路径中新建index.js用于存储全局变量:
index.js代码如下,这里定义了两个变量,playlist和playCurrentIndex,
import { createStore } from 'vuex'
export default createStore({
state: {
playlist:[
{al:{},}
],
playCurrentIndex:0,
},
getters: {
},
mutations: {
// 用来修改state中的playlist
setPlaylist:function (state,value) {
state.playlist = value
},
setPlayIndex:function (state,index) {
state.playCurrentIndex = index
}
},
actions: {
},
modules: {
}
})
1.修改
在组件中,用如下代码将api中的数组用于替换index.js中的playlist变量
关键代码:
this.$store.commit('setPlaylist',this.playlist.tracks);
2.使用
在组件中,用如下代码,调用index.js中的全局变量:
关键代码:
import {mapState,mapMutations} from 'vuex'
computed:{
...mapState(['playlist','playCurrentIndex'])
},
<img class="songPhoto" :src="playlist[playCurrentIndex].al.picUrl">
<div class="singName">{{playlist[playCurrentIndex].name}}</div>
<audio :src="`https://music.163.com/song/media/outer/url?id=${playlist[playCurrentIndex].id}.mp3`"></audio>
methods:{
console.log(this.playCurrentIndex)
// 或
console.log(this.$store.state.playCurrentIndex)
}
更多推荐
已为社区贡献4条内容
所有评论(0)