vue项目中js文件使用vue的this实例说明

vue中其他.js文件使用this实例

在main.js中引入vue,然后在vue文件中直接使用this(this指向的是vue实例),但是在实际开发中,我们往往会引入外部的js文件使用this,这个this就会指向window,并不是我们期待的vue实例,那么就需要重新引入vue文件(import Vue from ‘vue’),这样很麻烦。

在目前项目中我使用的方法是mian.js导出vue实例,然后在需要使用的js中引入。

main.js中导出vue

let vue = new Vue({
  router,
  store,
  // i18n,
  render: h => h(App)
}).$mount('#app');

export default vue

request.js中导入main.js并使用

import axios from 'axios';
import { getAccessToken, getRefreshToken, getAccessTokenTTL } from '@/utils/auth'
import _this from '../main.js'

const service = axios.create({
  timeout: 120000,
  baseURL: process.env.VUE_APP_BASE_API
  // withCredentials: true, // 跨域时携带cookies
})

service.interceptors.request.use(
  async config => {
    // 防止缓存,给get请求加上时间戳
    if (config.method === 'get') {
      const url = config.url
      url.indexOf('?') === -1 ? config.url = url + '?_=' + (new Date().getTime()) : config.url = url + '&_=' + (new Date().getTime())
    }
    const token = getAccessToken('token') 
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  err => Promise.reject(err)
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  async error => {
    switch (error.response.data.code) {
      case 910005: // 返回910005 缺失accessToken
      case 910006: // 返回910006 获取SESSIONID失败
      case 910007: // 返回910007 accessToken过期
      case 910008: // 返回910008 找不到用户信息
      case 910009: // 返回910007 refreshToken过期
        // console.log('跳转登录页');
        _this.$router.push('/login')
        break
      default:
        console.log('err' + error)
    }
    return Promise.reject(error)
  }
)
export default service

vue模板使用this问题

在Vue模板中,this是隐式的(这就是为什么console.log不能从模板中工作的原因),所以可以跳过它,使用store存储相应数据

<input :value="$store.state.shareUrl"/>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/weixin_42681295/article/details/120529319