欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue項(xiàng)目中js文件使用vue的this實(shí)例說明

 更新時間:2022年12月07日 08:37:27   作者:牛先森家的牛奶  
這篇文章主要介紹了vue項(xiàng)目中js文件使用vue的this實(shí)例說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

vue中其他.js文件使用this實(shí)例

在main.js中引入vue,然后在vue文件中直接使用this(this指向的是vue實(shí)例),但是在實(shí)際開發(fā)中,我們往往會引入外部的js文件使用this,這個this就會指向window,并不是我們期待的vue實(shí)例,那么就需要重新引入vue文件(import Vue from ‘vue’),這樣很麻煩。

在目前項(xiàng)目中我使用的方法是mian.js導(dǎo)出vue實(shí)例,然后在需要使用的js中引入。

main.js中導(dǎo)出vue

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

export default vue

request.js中導(dǎo)入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('跳轉(zhuǎn)登錄頁');
        _this.$router.push('/login')
        break
      default:
        console.log('err' + error)
    }
    return Promise.reject(error)
  }
)
export default service

vue模板使用this問題

在Vue模板中,this是隱式的(這就是為什么console.log不能從模板中工作的原因),所以可以跳過它,使用store存儲相應(yīng)數(shù)據(jù)

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

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論