lrf402788946 4 years ago
parent
commit
e3a83a37c8
9 changed files with 153 additions and 40 deletions
  1. 2 1
      package.json
  2. 93 0
      src/layout/common/share.vue
  3. 0 14
      src/plugins/var.js
  4. 15 18
      src/router/index.js
  5. 5 2
      src/store/index.js
  6. 31 0
      src/store/weixin.js
  7. 1 3
      src/views/index.vue
  8. 5 1
      src/views/login.vue
  9. 1 1
      vue.config.js

+ 2 - 1
package.json

@@ -24,7 +24,8 @@
     "vue-meta": "^2.3.4",
     "vue-router": "^3.3.2",
     "vue-video-player": "^5.0.2",
-    "vuex": "^3.1.3"
+    "vuex": "^3.1.3",
+    "weixin-js-sdk": "^1.6.0"
   },
   "devDependencies": {
     "@vue/cli-plugin-babel": "~4.3.0",

+ 93 - 0
src/layout/common/share.vue

@@ -0,0 +1,93 @@
+<template>
+  <div id="share">
+    <van-button type="info" @click="toShare">分享</van-button>
+  </div>
+</template>
+
+<script>
+let wx = require('weixin-js-sdk');
+import { mapState, createNamespacedHelpers } from 'vuex';
+const { mapActions: weixin } = createNamespacedHelpers('weixin');
+export default {
+  name: 'share',
+  props: {},
+  components: {},
+  data: function() {
+    return {
+      wx: {},
+    };
+  },
+  created() {
+    this.init();
+  },
+  methods: {
+    ...weixin(['jsAuth']),
+    async init() {
+      const { path, query } = this.$route;
+      const { openid, ...others } = query;
+      let uri = `${path}`;
+      const keys = Object.keys(others);
+      if (keys.length > 0) {
+        const arr = keys.map(key => `${key}=${query[key]}`);
+        uri = `${uri}?${arr.join('&')}`;
+      }
+      const url = `${this.host}${uri}`;
+      const res = await this.jsAuth({ url });
+      if (this.$checkRes(res)) {
+        const { data } = res;
+        wx.config({
+          debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
+          appId: data.appid, // 必填,公众号的唯一标识
+          timestamp: data.timestamp, // 必填,生成签名的时间戳
+          nonceStr: data.noncestr, // 必填,生成签名的随机串
+          signature: data.sign, // 必填,签名
+          jsApiList: [
+            'updateAppMessageShareData', //朋友及QQ
+            'updateTimelineShareData', // 朋友圈及QQ空间
+          ],
+        });
+        wx.ready(() => {
+          console.log('in ready');
+          this.$set(this, 'wx', wx);
+        });
+        wx.error(res => {
+          console.log(res);
+        });
+      }
+    },
+    toShare() {
+      this.wx.updateAppMessageShareData({
+        title: '测试分享',
+        desc: '测试',
+        // imgUrl:''
+        link: 'http://free.waityou24.cn/',
+        success: res => {
+          console.log('in function:share success');
+          console.log(res);
+        },
+        error: err => {
+          alert('share is fail');
+          alert(JSON.stringify(err));
+        },
+      });
+    },
+  },
+  computed: {
+    ...mapState(['user', 'menuParams']),
+    pageTitle() {
+      return `${this.$route.meta.title}`;
+    },
+    host() {
+      return 'http://broadcast.waityou24.cn';
+    },
+    authUrl() {
+      return `${host}/api/article/auth`;
+    },
+  },
+  metaInfo() {
+    return { title: this.$route.meta.title };
+  },
+};
+</script>
+
+<style lang="less" scoped></style>

+ 0 - 14
src/plugins/var.js

@@ -1,24 +1,10 @@
 import Vue from 'vue';
 import _ from 'lodash';
 
-const getSiteId = () => {
-  let host = `${window.location.hostname}`; //`999991.smart.jilinjobswx.cn ${window.location.hostname}`
-  let schId;
-  host = host.replace('http://', '');
-  let arr = host.split('.');
-  if (arr.length > 0) {
-    schId = arr[0];
-    if (schId === 'smart') schId = 'master';
-    else `${schId}`.includes('localhost') || `${schId}`.includes('127.0.0.1') ? (schId = '99991') : '';
-    sessionStorage.setItem('schId', `${schId}`.includes('localhost') || `${schId}`.includes('127.0.0.1') ? '99991' : schId);
-  }
-  return schId;
-};
 const Plugin = {
   install(vue, options) {
     // 4. 添加实例方法
     vue.prototype.$limit = 10;
-    vue.prototype.$site = getSiteId();
   },
 };
 

+ 15 - 18
src/router/index.js

@@ -96,25 +96,22 @@ const router = new VueRouter({
 });
 
 router.beforeEach(async (to, form, next) => {
+  // 检查session中是否有user信息
+  store.commit('getUser');
+  const user = store.state.user;
+  if (!user) {
+    // 有没有openid
+    const { openid } = to.query;
+    if (openid) {
+      // 使用openid换取用户信息
+      const res = await store.dispatch('weixin/login', openid);
+      if (!res) console.warn('未获取到用户信息');
+    } else {
+      // 没有openid,很可能是没用微信浏览器打开
+      console.warn('未获取到用户信息');
+    }
+  }
   next();
-  // if (to.name == 'account_user') {
-  //   let res = await store.dispatch('login/toGetUser');
-  //   if (res && res.uid) {
-  //     next();
-  //   } else {
-  //     let key = sessionStorage.getItem('token');
-  //     let user = jwt.decode(key);
-  //     if (user && user.uid) {
-  //       store.commit('setUser', user, { root: true });
-  //       next();
-  //     } else {
-  //       next({ name: 'login' });
-  //     }
-  //   }
-  // } else {
-  //   let res = await store.dispatch('login/toGetUser');
-  //   next();
-  // }
 });
 const originalPush = VueRouter.prototype.push;
 VueRouter.prototype.push = function push(location, onResolve, onReject) {

+ 5 - 2
src/store/index.js

@@ -5,12 +5,13 @@ import upload from './upload';
 import refute from './refute';
 import topic from './topic';
 import service from './service';
+import weixin from './weixin';
 
 Vue.use(Vuex);
 
 export default new Vuex.Store({
   state: {
-    user: {},
+    user: undefined,
   },
   mutations: {
     setUser(state, payload) {
@@ -18,7 +19,8 @@ export default new Vuex.Store({
       state.user = payload;
     },
     getUser(state, payload) {
-      state.user = jwt.decode(JSON.parse(sessionStorage.getItem('user')));
+      let user = sessionStorage.getItem('user');
+      if (user) state.user = JSON.parse(user);
     },
   },
   actions: {},
@@ -28,5 +30,6 @@ export default new Vuex.Store({
     refute,
     topic,
     service,
+    weixin,
   },
 });

+ 31 - 0
src/store/weixin.js

@@ -0,0 +1,31 @@
+import Vue from 'vue';
+import Vuex from 'vuex';
+import _ from 'lodash';
+import axios from 'axios';
+Vue.use(Vuex);
+const api = {
+  user: `/api/article/wxUser`,
+  jsapi: `/api/article/jsapi`,
+};
+const state = () => ({});
+const mutations = {};
+
+const actions = {
+  async login({ commit }, openid) {
+    const res = await axios.get(`${api.user}?openid=${openid}`);
+    if (res.data.errcode === 0) {
+      commit('setUser', res.data.data, { root: true });
+      return true;
+    }
+  },
+  async jsAuth({ commit }, payload) {
+    const res = await this.$axios.$post(api.jsapi, payload);
+    return res;
+  },
+};
+export default {
+  namespaced: true,
+  state,
+  mutations,
+  actions,
+};

+ 1 - 3
src/views/index.vue

@@ -38,9 +38,7 @@ export default {
     this.$set(this, `clientHeight`, clientHeight);
   },
   methods: {
-    search({ skip = 0, limit = 10, searchName, ...info } = {}) {
-      console.log(searchName);
-    },
+    search({ skip = 0, limit = 10, searchName, ...info } = {}) {},
   },
   computed: {
     ...mapState(['user']),

+ 5 - 1
src/views/login.vue

@@ -7,17 +7,21 @@
         <van-button round block type="info" native-type="submit">提交</van-button>
       </div>
     </van-form>
+    <share></share>
   </div>
 </template>
 
 <script>
+import share from '@/layout/common/share.vue';
 const _ = require('lodash');
 import { mapState, createNamespacedHelpers } from 'vuex';
 const { mapActions: mapLogin } = createNamespacedHelpers('login');
 export default {
   name: 'login',
   props: {},
-  components: {},
+  components: {
+    share,
+  },
   data: function() {
     return {
       form: {},

+ 1 - 1
vue.config.js

@@ -22,7 +22,7 @@ module.exports = {
         target: 'http://broadcast.waityou24.cn',
       },
       '/api': {
-        target: 'http://192.168.1.19:10010',
+        target: 'http://broadcast.waityou24.cn', //http://192.168.1.19:10010
         changeOrigin: true,
         ws: true,
       },