先上效果:
思路:网上的api不一定免费,且有一堆限制,不如自己动手丰衣足食。
利用uni-app会提供给每个开发者一个免费的云服务,将携带心灵鸡汤或诗词的json保存到云服务器上,再利用uni.request将文件请求过来即可。
// src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const modulesFiles = require.context('./modules', true, /\.js$/)
// 自动导入模块文件中的所有vuex模块
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
const value = modulesFiles(modulePath)
modules[moduleName] = value.default
return modules
}, {})
export default new Vuex.Store({
state:{
passId: ''
},
modules
})
// src/store/modules/scene.js
// store 文案列表存储
const scene = {
namespaced: true, //为了解决不同模块命名冲突的问题
state: {
soupList: [],
currentSoup: ''
},
mutations: {
setSoupList(state, {soupList, currentSoup}) {
state.soupList = soupList
state.currentSoup = currentSoup
}
},
actions: {
getSoupList({ commit }, baseUrl) {
let soupList = []
// 通过接口获取提前写好的鸡汤文列表
return new Promise((resolve, reject) => {
uni.request({
url: `${baseUrl}/barcode/SoulChickenSoup.json`,
success: (item) => {
// #ifdef MP-BAIDU
soupList = JSON.parse(item.data)
// #endif
// #ifndef MP-BAIDU
soupList = item.data;
// #endif
const randomIndex = Math.floor(Math.random() * soupList.length);
const currentSoup = soupList[randomIndex];
commit('setSoupList', {soupList, currentSoup});
resolve(soupList);
},
fail: (err) => {
reject(err);
}
})
})
}
}
}
export default scene
// src/store/json/SoulChickenSoup.json
[
"昨夜西风凋碧树,独上高楼,望尽天涯路",
"长风破浪会有时,直挂云帆济沧海",
"博观而约取,厚积而薄发",
"不飞则已,一飞冲天;不鸣则已,一鸣惊人",
...
]
// src/App.vue
<script>
import SoulChickenSoup from './store/json/SoulChickenSoup.json'
import { mapActions, mapMutations } from 'vuex';
export default {
globalData: {
baseUrl: 'https://***',
},
onLaunch: function() {
this.getSoupList(this.globalData.baseUrl).then(res => {
}).catch(err => {
// 如果接口报错,默认使用包内的json文件,防止报错
const soupList = SoulChickenSoup
// 根据数组长度随机选择一条数据展示
const randomIndex = Math.floor(Math.random() * soupList.length);
const currentSoup = soupList[randomIndex];
// 数据塞入store
this.setSoupList({soupList, currentSoup})
})
},
methods: {
...mapActions('scene', ['getSoupList']),
...mapMutations('scene', ['setSoupList']),
}
}
</script>
// src/pages/index/index.vue
// 最终展示的位置
<view v-if="currentSoup" class="soup-class">{{currentSoup}}</view>
import { mapState } from 'vuex'
computed: {
...mapState({
currentSoup: state => state.scene.currentSoup
}),
}
小程序效果体验(欢迎咨询客服索取json文件):
更多详细代码请关注公众号索取(备注:公众号):