第一次将vue实用在项目中,遇到的问题不老少;在一个小项目中最初将数据加载的代码直接写在了初始化的界面中,后来的需求修改使得数据加载的程序越来越庞大(其实也就是比最初的多了一点点),不仅看起来不美观,而且在多处调用时也十分不方便。
于是,就像把数据加载的代码独立出来放到JS文件中来使用,可直接新建JS文件并把代码扔进去似乎是不行。。。
网上各种找,最终结局了眼前的问题。

编写自定义JS文件

JS文件中定义export default,并在install中通过定义Vue.prototype.xxx设置自己的方法。

loaddata.js文件代码片段:

    export default {
      install(Vue) {
        Vue.prototype.loadRptDate = function() {
          let that = this
          this.$http.get("itf/tc/query_date/")
            .then(function(res) {
              store.commit('setRptYear', res.data.ryear);
              store.commit('setRptWeek', res.data.rweek);
              store.commit('setRptDate', res.data.rdate);
              that.loadData();
            })
            .catch(function(err){
              console.log(err)
            });
        }
        Vue.prototype.loadData = function() {
          ... ...
          Load Something ...
          ... ...
        }
      }
    }

引用JS文件

在 main.js 中引入 loaddata.js import loadData from './loaddata.js' 并使用 Vue.use(loadData) ,这样之后,就可以在整个项目中就都可以通过 this 来使用自定义的函数了。

引用代码片段:

    import loadData from './loaddata.js'
    Vue.use(loadData)

使用JS文件中的函数

调用代码片段:

    export default {
      name : 'App',
      store,
      components: {
        
      },
      methods : {
        load() {
          if (store.state.isQueryDate) {
            this.loadData();
          } else {
            this.loadRptDate();
          }
        },
        ... ...
      },
      data() {
        return {
          message: 'message',
          ... ...
        }
      },
      mounted(){
        this.load();
      }
    }

alt