uni-app:第五章 vuex使用 &ajax配置

  • 創建store
    在這裏插入圖片描述
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
	state: {
		city: "北京市",
		nowPlayingList:[]
	}, 
 
   //操作變量的方法
	mutations: {

	},
	//異步
	actions: {
	
	},
})

  • 將store引入main.js
import Vue from 'vue'
import App from './App'
//引入store
import store from "./store"
Vue.config.productionTip = false
/**
 * 引入store
 */
Vue.prototype.$store=store;

App.mpType = 'app'


const app = new Vue({
    ...App
})
app.$mount()
  • 創建ajax 文件

在這裏插入圖片描述

const BASE_URL = "https://api.douban.com/v2/movie"

/**
 * 方法調用
 */
export const getInTheaters = params => (
	new Promise((resolve, reject) => {
		uni.request({
			url: `${BASE_URL}/in_theaters`,
			data: params,
			header: {
				"content-type": "json"
			},
			success: (res) => {
				resolve(res);
			}

		});
	})
)

  • 實例一:在store中異步操作
import Vue from 'vue'
import Vuex from 'vuex'
//導入騰訊地圖api
import QQMapWX from "../static/js/qqmap-wx-jssdk.min.js"
Vue.use(Vuex);

import {
	getInTheaters
} from "../apis/index.js"

export default new Vuex.Store({
	state: {
		city: "北京市",
		nowPlayingList:[]
	},
	mutations: {

	},
	//異步
	actions: {
		getCity(cotext) {
			uni.authorize({
				scope: 'scope.userLocation',
				success() {
					//引入騰訊地圖api
					let qqmapsdk = new QQMapWX({
						key: 'GXNBZ-YM3CQ-AYI56-GBTQ2-HEODS-FNFCM'
					});
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							qqmapsdk.reverseGeocoder({
								location: {
									latitude: res.latitude,
									longitude: res.longitude
								},
								success: function(res) {
									cotext.state.city = res.result.address_component.city;
									getInTheaters({
										apikey: "0b2bdeda43b5688921839c8ecb20399b",
										start: 0,
										count: 10,
										city: cotext.state.city
									}).then(res => {
										console.log(res);
										cotext.state.nowPlayingList=res.data.subjects;
									})
								}
							})
						}
					});
				},
				fail(res) {
					console.log(res);
					uni.showToast({
						title: '需要獲取位置',
						icon: 'none',
						duration: 2000
					});
				}
			})
		}
	},
})

  • 調用getCity接口
    this.$store.dispatch(“getCity”)
<template>
	<view>
		<image :src="nowPlayingList[0].images.large"/>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				
			};
		},
		// 計算
		computed:{
			nowPlayingList(){
				return this.$store.state.nowPlayingList;
			}
		},
		onReady() {
			this.$store.dispatch("getCity")
		}
	}
</script>

<style lang="less">

</style>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章