简体   繁体   中英

Use vue-router in a mixin

I have my main.js set up like the following:

import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource';

Vue.config.productionTip = false;

Vue.use(VueRouter);
Vue.use(VueResource);

Vue.mixin({
  methods: {
    get_req: function(url)  {
        Vue.http.get(url, {
            before(request) {
                // before_callback(request);
            }
            }).then(response => {
                // success_callback(response);
            }, response => {
                if(response.status == 404) {
                    Vue.router.push({name: '404'}); // <--- ERROR HERE
                }

            }).then(response => {
                // always_callback(response);
        });
    }
  }
});

const router = new VueRouter({
  routes: [
        {
            path: '/',
            component: Home,
            meta: {page_title: 'Home'}
        },
        // ...
    ]
});

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  router: router
});

The error is:

TypeError: Cannot read property 'push' of undefined

So, I know that Vue.router is not defined when I call the mixin method, and I know that a workaround for this is to pass the router itself as argument like something this.get_req(this.$router, 'http://example.com/users/5') .

But I trust that there must a better way.

Define your router first, then use it in the mixin.

import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource';

Vue.config.productionTip = false;

Vue.use(VueRouter);
Vue.use(VueResource);

// define the router here
const router = new VueRouter({
  routes: [
        {
            path: '/',
            component: Home,
            meta: {page_title: 'Home'}
        },
        // ...
    ]
});

Vue.mixin({
  methods: {
    get_req: function(url)  {
        Vue.http.get(url, {
            before(request) {
                // before_callback(request);
            }
            }).then(response => {
                // success_callback(response);
            }, response => {
                if(response.status == 404) {
                    // Use the router variable you just defined
                    router.push({name: '404'}); 
                }

            }).then(response => {
                // always_callback(response);
        });
    }
  }
});


new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  router: router
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM