1
votes

I'm setting up a brand new Vue 2 project. Due to compatibility issues with one of the libraries I need to use, I can't yet move to Vue 3.

I have a very basic setup at the moment, folder structure something like this:

/
App.vue
main.js
router.js

/pages
AboutUs.vue
Home.vue

If I don't use Vue Router, and just import the AboutUs page into App.vue and call its tag in the template, it displays as expected.

When I instead use the Vue Router to render it in the <router-view /> tag in App.vue, I get the error message:

[Vue warn]: Failed to mount component: template or render function not defined.

I suspect that means I'm doing something wrong in the router but I can't see what.

main.js

import Vue from 'vue'
import App from './App.vue'

import router from 'router.js'

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

App.vue

<template>
  <div id="app">
    <router-link to="/">Home</router-link>
    <router-link to="/About">About</router-link>
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

router.js

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const About = require('../pages/AboutUs')
const Home = require('../pages/Home')

const routes = [
  {
    path: '/about',
    name: 'About',
    component: About
  },
  {
    path: '*',
    name: 'Home',
    component: Home
  }
]

const router = new VueRouter({
  linkExactActiveClass: '',
  routes
})

export default router

About.vue

<template>
  <div>
    <h1>About</h1>
  </div>
</template>

<script>
export default {
    
}
</script>
1
From the official docs, it looks like the correct form is <router-view></router-view> aka router-view is not a self closing tag. router.vuejs.org/api/#router-viewkissu
@kissu The docs show it that way, but it's ok for any component to self close in Vue CLI. In fact, it's strongly recommended to do so. (This is not the case for in-DOM templates)Dan

1 Answers

1
votes

es6 import

Try to use an es6 import instead of require:

import About from '../pages/AboutUs'
import Home from '../pages/Home'

Then your route syntax will work as is. This is because when you use require, you get the whole module rather than the Component export from the module.

-or-

require

Alternatively, if you wanted to continue using require, you would need the following syntax, using the default property of the module:

const About = require('../pages/AboutUs')
const Home = require('../pages/Home')
const routes = [
  {
    path: '/about',
    name: 'About',
    component: About.default
  },
  {
    path: '*',
    name: 'Home',
    component: Home.default
  }
]