本样例以qq音乐搜索接口为样例,实现的效果为:点击上图中四个歌手的名称,把相应的音乐列表展示在右侧框框中,但如果点过一次后的接口则不再请求接口,使用vuex中第一次缓存下的数据展示。也就最后不管点击多少次,请求接口的次数最大为4次。
代码实现如下:
1: api.js
export function getNewQqMusic(params) {
return fetch({
url: "/splcloud/fcgi-bin/smartbox_new.fcg",
method: "GET",
params,
});
}
2:页面布局和方法绑定
<div class="cache-content">
<div class="title-content">
<div
v-for="item in songerName"
:key="item.id"
class="songer-name"
@click="searchSong(item.name)"
>
{{ item.name }}
</div>
</div>
<div class="content">
<div v-for="item in cacheMusicList[activeName]" :key="item.id">
<span>{{ item.name }}</span>
<span>{{ item.singer }}</span>
</div>
</div>
</div>
3:样式
.cache-content {
width: 400px;
height: 400px;
background: red;
display: flex;
}
.title-content {
width: 60px;
height: 400px;
background: greenyellow;
}
.content {
width: 340px;
height: 400px;
background: #ccc;
}
.songer-name {
line-height: 42px;
background: orange;
text-align-last: justify;
}
.songer-name:nth-child(2n) {
background: goldenrod;
}
4:方法实现
import { mapActions, mapState } from "vuex";
export default {
name: "MusicList",
data() {
return {
// musicList: [],
songerName: [
{ id: 1, name: "王菲" },
{ id: 2, name: "王力宏" },
{ id: 3, name: "小猫" },
{ id: 4, name: "王狗" },
],
activeName: "",
};
},
created() {
console.log("this.$stroe", this.$store);
},
methods: {
...mapActions("music", ["getQqMusicInterface", "getCacheQqMusicInterface"]), // 接口
// 点击名字搜索音乐
searchSong(name) {
// console.log("name", name);
let str =
"_=1645232392501&cv=4747474&ct=24&format=json&inCharset=utf-8&outCharset=utf-8¬ice=0&platform=yqq.json&needNewCode=1&uin=1251271810&g_tk_new_20200303=2085573607&g_tk=2085573607&hostUin=0&is_xml=0&key=%E5%91%A8%E6%9D%B0";
let params = {};
str.split("&").map((ele) => {
let arr = ele.split("=");
params[arr[0]] = arr[1];
});
params.key = name;
this.activeName = name;
console.log("params", params);
let lst = this.cacheMusicList[name];
if (!(lst && lst.length > 0)) {
this.getCacheQqMusicInterface(params);
}
},
},
computed: {
...mapState("music", ["musicList", "cacheMusicList"]),
},
};
5:vuex:music.js
import { getNewQqMusic } from "@/utils/api";
export default {
namespaced: true,
state: {
str: "hello world",
musicList: [],
cacheMusicList: {}, // 测试缓存的musiclist
},
getters: {},
mutations: {
updateMusicList(state, payload) {
state.musicList = payload;
},
// 根据条件更新缓存music,有则用,无则更新
updateCacheMusicList(state, payload) {
state.cacheMusicList[payload.k] = payload.v;
state.cacheMusicList=JSON.parse(JSON.stringify(state.cacheMusicList))
},
},
actions: {
getQqMusicInterface(store, payload) {
getNewQqMusic(payload).then((res) => {
// console.log('res store',res)
store.commit("updateMusicList", res.data.data.song.itemlist);
});
},
// 测试缓存
getCacheQqMusicInterface(store, params) {
getNewQqMusic(params).then((res) => {
// console.log("payload", payload, "rs", res);
let payload = { k: params.key, v: res.data.data.song.itemlist };
store.commit("updateCacheMusicList", payload);
});
},
},
};
最后实现效果如下:
不管最后点击多少次,接口最多总是调的四次。