zoukankan      html  css  js  c++  java
  • 前后端交互2 vuex存储token

    1. 在vuex中新增login、initlogin方法

      login方法作用是将token和user信息存入缓存

      initLogin方法的作用是初始化聊天对象

     

    import $U from '@/common/free-lib/util.js'
    import $H from '@/common/free-lib/request.js'
    import Chat from '@/common/free-lib/chat.js' export default { state: { user: {}, chat: null }, actions: { // 登陆后的处理 login({ state, dispatch }, user) { // 存到state中 state.user = user; // 存储到本地存储中 $U.setStorage('token', user.token) $U.setStorage('user', JSON.stringify(user)) $U.setStorage('user_id', JSON.stringify(user.id))

                   // 连接websocket
                   state.chat = new Chat({
                   url: 'ws://127.0.0.1:7001/ws'
                  })
    		},
    		// 初始化登录状态
    		initLogin( {state, dispatch }) {
    			// 拿到存储数据
    			let user = $U.getStorage('user')
    			if (user) {				
    				// 初始化登录状态
    				state.user = JSON.parse(user)
    				
    				// 连接websocket
    				state.chat = new Chat({
    					url: 'ws://127.0.0.1:7001/ws'
    				})
    				
    				console.log(state.chat+ '=============')
    				console.log('====================')
    			}
    		}
    	}
    }
      
    

     

    2. 新建聊天Chat类

    import $U from './util.js'
    import $H from './request.js'
    import $C from './config.js'
    
    class Chat {
    	constructor(arg) {
    	   // 初始化url、是否在线
    	    this.url = arg.url
    		this.isOnline = false
    		this.socket = null
    		
    		// 获取当前用户相关信息
    		const user = $U.getStorage('user')
    		this.user = user ? JSON.parse(user) : {}
    		
    		// 初始化聊天
    		// To表示当前聊天对象的对方
    		this.To = false
    				
    		// 连接和监听
    		if (this.user.token) {
    			this.connectSocket()
    		}
    	}
    	
    	// 连接socket
    	connectSocket() {
    		// 连接websocket( 注意:需要添加token信息)
    		this.socket = uni.connectSocket({
    			url: this.url + '?token='+this.user.token,
    			complete: () => {}
    		})
    		
    		// 监听连接成功
    		this.socket.onOpen(() => this.onOpen())
    		
    		// 监听断开
    		this.socket.onClose(() => this.onClose())
    		
    		// 监听接收信息
    		this.socket.onMessage(res => this.onMessage(res))
    		
    		// 监听错误
    		this.socket.onError(() => this.onError())
    	}
    	
    	onOpen() {
    		// 用户上线
    		this.isOnline = true
    		console.log('socket连接成功')
    		
    		// 获取用户离线消息
    	}
    	
    	onClose() {
    		// 用户下线
    		this.isOnline = false
    		this.websocket = null
    		console.log('socket关闭')
    	}
    	
    	onError() {
    		// 用户下线
    		this.isOnline = false
    		this.socket = null
    		console.log('socket连接错误')
    	}
    	
    	// 监听接收消息
    	onMessage(res) {
    		console.log(res)
    	}
    	
    	// 创建聊天对象
    	createChatObject(detail) {
    		this.To = detail
    		console.log('创建聊天对象', this.To)
    	}
    	
    	// 销毁聊天对象
    	destoryChatObject() {
    		this.To = null
    		console.log('销毁聊天对象', this.To)
    	}
    	
    	// 组织发送信息格式
    	formatSendData(params) {
    		return {
    			id: 0,// 唯一id, 用于撤回
    			from_avatar: this.user.avatar,// 发送者头像
    			from_name: this.user.name,// 发送者昵称
    			from_id: this.user.id,// 发送者id
    			to_id: this.To.user_id,// 接收人人/群 id
    			to_name: this.To.nickname,// 接收人/群 名称
    			to_avatar: this.To.avatar,// 接收人/群 头像
    			chat_type: 'user' ,//接收;类型
    			type: params.type,// 消息类型
    			data: params.data,
    			potions: params.options ? params.options : {},
    			create_time: (new Date()).getTime(),
    			isremove: 0,
    			sendStatus: 'pending'// 发送状态
    		}
    	}
    }
    
    export default Chat
    

      

    3. 在登录页面Login.vue中,当点击按钮触发submit事件时,发送登录post请求,将token和user信息添加到缓存, 且连接websocket

    submit() {
    		$H.post('/'+this.type, this.form, {
    			token: false,
    		}).then(res => {
    			if (this.type === 'login') {
    				this.$store.dispatch('login', res)
    				uni.showToast({
    					title: '登录成功',
    					icon: 'none'
    				});
    				// 跳转到tabbar页面需要用switTab
    				return uni.switchTab({
    					url:"/pages/tabbar/index/index"
    				})
    			}
    			// 注册
    			this.changeType()
    			uni.showToast({
    				title: '注册成功',
    				mask: false,
    				duration: 1500
    			});
    		})
    	}
    

      

  • 相关阅读:
    phpcms 任意位置获取用户头像
    php微信公众帐号发送红包
    nginx解决502错误
    phpcms v9 万能字段使用
    0转换为万
    温故而知新(三)
    温故而知新(一)
    基础积累,来自其他网站的链接
    GCD多线程 在子线程中获取网络图片 在主线程更新
    iOS9 中的一些适配问题
  • 原文地址:https://www.cnblogs.com/zhanghaoblog/p/12636540.html
Copyright © 2011-2022 走看看