美文网首页
vue项目外部引入的js文件使用vue实例的方法

vue项目外部引入的js文件使用vue实例的方法

作者: zkzhengmeng | 来源:发表于2019-07-18 08:39 被阅读0次

方式一 :

  1. 在getData.js 定义一个变量_this(用来接受vue)用来接收vue,再写一个getVue方法传入的参数是vue,并导出这个方法。
let _this = '' ; 定义一个_this变量,用来代替this(vue)
function GetDateTime() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate(); //
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}
  export default {
  // 写一个此文件引入vue的方法,然后export导出去
    getVue(vue) {
        _this = vue
    }
}

2.在main.js中执行getData.js抛出的这个getVue方法并出入vue实例

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from "axios"
import store from './vuex/store'
import GetDateTime from './getData.js' //(根据自己的路径正确引入地址)
Vue.prototype.$time = GetDateTime;  //其中$time为新命的名。
var vue = new Vue({
    el: '#app',
    router,
    components: {App},
    template: '<App/>'
})
Vue.prototype.http = http
//挂载$time的时候执行引入vue的方法
Vue.prototype.$time.getVue(vue) // 传入vue实例

方法二 :

  1. 在main.js中定义var vue = new Vue({})实例 , 抛出 export default vue的实例
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from "axios"
import store from './vuex/store'
import GetDateTime from './getData.js'
Vue.config.productionTip = false
Vue.prototype.$time = GetDateTime;  //其中$time为新命的名。
Vue.prototype.$http = axios
Vue.prototype.$http = axios.create({
    headers: {
        "Content-Type": "application/json;charset=UTF-8"
    }, //后台需要格式配置
    baseURL: "/api/", //开发环境请求地址
    //baseURL: "https://www.baidu.com/", //生产环境请求地址
    transformRequest: [function(data) { //数据格式转换
        data = JSON.stringify(data)
        console.log(data)
        return data
    }]
});

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

export default vue

2.在getData.js中引入main.js文件

import context  from './main.js'   // 导入main.js文件

function GetDateTime() {
 console.log(context.xxx) // 直接调用vue实例即可
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate(); //
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}
    export default {
       GetDateTime 
    }

相关文章

网友评论

      本文标题:vue项目外部引入的js文件使用vue实例的方法

      本文链接:https://www.haomeiwen.com/subject/oqfklctx.html