简体   繁体   中英

How I use vue-router with vue 2.x versions

import Vue from 'vue' import Vuex from 'vuex' import VueRouter from 'vue-router' import 'es6-promise/auto'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue'

//import About from "./components/About.vue"

Vue.config.productionTip = false
Vue.use(ElementUI);
Vue.use(Vuex)
Vue.use(VueRouter)

const store = new Vuex.Store({ ... })

const routes = [
  { path: '/about', component: { template: '<div>foo</div>' } },
]

const router = VueRouter({
  routes, // short for `routes: routes`
})

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

I try to use router but it gives err below:

Uncaught TypeError: this is undefined
    VueRouter vue-router.esm.js:2699
    <anonymous> main.js:84
    js app.js:1351
    __webpack_require__ app.js:849
    fn app.js:151
    1 app.js:1364
    __webpack_require__ app.js:849
    checkDeferredModules app.js:46
    <anonymous> app.js:925
    <anonymous> app.js:928
vue-router.esm.js:2699
    VueRouter vue-router.esm.js:2699
    <anonim> main.js:84
    js app.js:1351
    __webpack_require__ app.js:849
    fn app.js:151
    1 app.js:1364
    __webpack_require__ app.js:849
    checkDeferredModules app.js:46
    <anonim> app.js:925
    <anonim> app.js:928

I create my project vue cli and then I install vue-router with npm -i, why its not work this way or should I add with vue add router cli command?

Here is my versions:

    "vue": "^2.6.12",
    "vue-router": "^3.2.0",
    "vuex": "^3.6.2"
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "^4.5.11",
    "@vue/cli-service": "~4.5.0",
    "babel-eslint": "^10.1.0",
    "babel-plugin-component": "^1.1.1",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "vue-template-compiler": "^2.6.11"

The error is not an error in VueRouter import but for VueRouter usage.

VueRouter function is a constructor to get router Instance. In your code, you have to do this to fix your problem:

const router = new VueRouter({
  routes, // short for `routes: routes`
})

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