Vue Router import not working with require - vue.js

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>

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
}
]

Related

Vue-router: do i need to define the default route for vue-router

Experimenting with vue-router, when i click on <router-link to="/about">Go to About</router-link> it doesnt redirect me to anywhere so for example: if i was on localhost:8080/#/ and i click the Go to About button, i still remain on localhost:8080/#/. Also if i change the url directly to localhost:8080/#/about nothing happens (ie no change to the website as if i am still on localhost:8080/#/)
The code:
/router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{
path: '/about',
component: () => {
import ('../views/About.vue');
}
}
]
const router = new VueRouter({
routes
})
export default router;
./App.vue
<template>
<div>
<div id='nav'>
<router-link to="/about">Go to Foo</router-link>
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
components: {
//
},
data: () => ({
//
}),
};
</script>
./views/About.vue
<template>
<p>Testing out vue-routes</p>
</template>
./main.js
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import store from './store';
import router from './router';
Vue.config.productionTip = false;
new Vue({
vuetify,
store,
router,
render: h => h(App)
}).$mount('#app')
I tried running the following code. it gave no error on serving. (I am also using vuetify and vuex but i dont think that is the problem?)
EDIT
I have edited the code such that it works by creating another vue app and using the default that vue has provided with but i cant seem to understand why the edited code works and why the previous code ^^ above didnt. It seems like the reason was that the default localhost:8080/#/ needs to have its own route in ./App.vue as well and is not there by default? can someone confirm this (can't seem to find something like this explanation online?)
Revised working code:
./App.vue
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</div>
</template>
./views/Home.vue
<template>
<h1>This is the home page</h1>
</template>
<script>
export default {
name: 'Home',
components: {
//
},
data: () => ({
//
}),
};
</script>
./main.js
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import store from './store';
import router from './router';
Vue.config.productionTip = false;
new Vue({
vuetify,
store,
router,
render: h => h(App)
}).$mount('#app')
./router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router';
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/about",
name: "About",
component: () =>
import("../views/About.vue")
}
];
const router = new VueRouter({
routes
})
export default router;
./views/About.vue
<template>
<p>Testing out vue-routes</p>
</template>
You need to have a <router-view/> where the routes are going to resolve.
You can read more about it here: documentation

using vue-router to redirect to different pages

I have a vue application which dose simple inserts and i am trying to use vue router to redirect to different pages for example when i load /postComponent and /userComponent they will be on separate pages not all in one page when loading the localhost:8080
app.js
<template>
<div id="app">
<router-link to="/postcomponent">post</router-link>
<router-link to="/usercomponent">user</router-link>
<router-view/>
</div>
</template>
<script>
import PostComponent from './components/postComponent';
import userComponent from './components/userComponent';
export default {
name: 'app',
components: {
PostComponent,
userComponent
}
};
</script>
routes.js
import Vue from 'vue'
import App from '/client/src/App'
import VueRouter from 'vue-router'
import postComponent from '/client/src/components/postComponent';
import userComponent from '/client/src/components/userComponent';
vue.use(VueRouter);
Vue.config.productionTip = false
const routes = [
{
path: '/postcomponent',
name: 'postcomp',
component: postComponent
},
{
path: '/usercomponent',
name: 'usercomp',
component: userComponent
},
];
new Vue({
routes,
render: h => h(App),
}).$mount('#app')
postComponent
<script>
import postService from '../postService';
export default {
name: 'postComponent',
data() {
return {
posts: [],
error: '',
topic: '',
price: '',
location: '',
provider: ''
}
},
index.js
const express = require ('express');
const bodyparser = require ('body-parser');
const cors = require ('cors');
const app = express();
app.use(bodyparser.json());
app.use(cors());
const posts = require('./api/posts');
const users = require('./api/users');
app.use('/api/posts', posts);
app.use('/api/users', users);
const port = process.env.port || 500;
app.listen(port, () => console.log(`Server started on port ${port}`));
im getting the following error
https://i.stack.imgur.com/42Ka3.png
UPDATE ** :
App.vue :
<template>
<div id="app">
<router-link to="/postcomponent">post</router-link>
<router-link to="/usercomponent">user</router-link>
<router-view/>
</div>
</template>
Inside Routes.js import statements and paths :
import PostComponent from "#/components/PostComponent";
import UserComponent from "#/components/UserComponent";
const routes = [
{
path: '/postcomponent',
name: 'postcomp',
component: PostComponent
},
{
path: '/usercomponent',
name: 'usercomp',
component: UserComponent
},
];
PostComponent :
<template>
Post Comp
</template>
<script>
export default {
name: "PostComponent"
}
</script>
User Comp :
<template>
User Comp
</template>
<script>
export default {
name: "PostComponent"
}
</script>
UPDATE * :
remove those unnecessary imports on app file
I think its better to first have a look at Vue-router at https://router.vuejs.org/
SPA stands for Single Page Application means that all of your components eventually will execute on a single *.html file. this means that in SPA, you cant just redirect your client to another url and perform another HTTP request and still be on the same Vue SPA!. because then you will probably get new html/css and javascript files to execute and render.all you can do is 1.use vue router to specify on which path, what component should render. when you describe your router using VueRouter thats exactly what you are going to do!, config your router and tells him on which path, what component you should render.
there is no way that you can redirect your client to another domain and still be on the same SPA and loads your components BUT !
as i can see in your codes there is a way to achieve what you want. there are some problems in your code but i'll show you how you can config two routes to achieve something like that.
i assume that you have those two components postComponent and userComponent ready.
first we have to import those in our routes.js :
import postComponent from 'PATH_TO_COMP';
import userComponent from 'PATH_TO_COMP';
note that you can use '#' as an alias for /src in your directory
first we have to specify two routes, for /postcomponent and /usercomponent,
we doing it by adding two objects to routes array in VueRouter, we can specify a name for our routes and we must specify a component which will render on that router,
routes : [
{path : "/postcomponent", name :"postComp", component:postComponent},
{path : "/usercomponent", name :"userComp", component:userComponent}
]
so now we have to implement our app file to say that where we want this components to render, we use empty <router-view/> tag to show that,
now everything is set, you can switch between routes using <router-link> tag like below :
<router-link to="/postcomponent" >Show me post component :)</router-link>
and you will see that when you go to http://localhost:8080/postcomponent your postComponent will render and sits on your <router-view/> !

Can't see named routes

I'm sure i'm doing something stupid, but i just can't get this to work.
I defined routes in a separate js file, imported that into a newly created router, that i mounted in vue.
In the vue devtools i do see my named routes, but where the RouterView is in the vue devtools, the html shows
Routes.js:
import Home from '#/Views/Home.vue';
import NewProefwerk from '#/Views/NewProefwerk.vue';
const routes = [
{
path: '/',
name: 'home',
Component: Home
},
{
path: '/Nieuw',
name: 'new',
Component: NewProefwerk
}
];
export default routes;
main.js:
import VueRouter from 'vue-router';
import routes from '#/Routes'
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
base: '/',
routes
})
new Vue({
router,
render: h => h(App)
}).$mount('#app');
App.vue:
<template>
<div id="app">
<Navigation></Navigation>
<router-view></router-view>
</div>
</template>
<script>
import Navigation from '#/components/Navigation.vue';
export default {
name: 'app',
components: {
Navigation
}
};
</script>
Try to change Component to component.

Vue router link add object in the url

This is my setting:
main.js creates a vue and attaches the component App to an element in the dom
router.js sets the routs
App.vue has the router-view and a few router-links
Problem:
the link <router-link to="/admin">Admin1</router-link> works fine
the link <router-link to="{name: 'admin'}">Admin2</router-link> doesn;t work and adds to the url bar: #/{name: 'admin'}
Am I using the router in the wrong way?
Below my files in details
main.js
import Vue from 'vue'
import router from './router'
import App from './App'
new Vue({
router,
el: '#app',
components: { App },
template: '<App/>',
data: {
}
})
router.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Marketplace from '#/components/Marketplace'
import Admin from '#/components/Admin'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/marketplace',
name: 'marketplace',
component: Marketplace
},
{
path: '/admin',
name: 'admin',
component: Admin
}
]
})
App.vue
<template>
<div id="app">
<p>
<router-link to="/">Home</router-link>
<router-link to="/admin">Admin1</router-link>
<router-link to="{name: 'admin'}">Admin2</router-link>
</p>
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
In order for your to="{name: admin}" to work without adding the char #, do the following inside your router config file.
Also you are supposed to use the v-bind for to="".
Use v-bind:to="{name: 'admin'}" or :to="{name: 'admin'}"
Example:
export default new Router({
mode: 'history',
// whatever you have
})
Source: https://router.vuejs.org/en/essentials/history-mode.html

Failed to mount component: template or render function not defined

I'm trying to use vue-router to display routed components below my navbar component but I get an error specified in the title.
Here is my code:
main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import app from './app';
Vue.use(VueRouter);
const foo = {
template: '<div>foo</div>',
};
const bar = {
template: '<div>bar</div>',
};
const routes = [
{
path: '/',
component: foo,
},
{
path: '/bar',
component: bar,
},
];
const router = new VueRouter({
mode: 'history',
routes,
});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(app),
});
app.vue
<template>
<div id="app">
<fs-navbar/>
<main>
<router-view/>
</main>
</div>
</template>
<style scoped lang="scss">
</style>
<script>
import fsNavbar from './components/fs-navbar';
export default {
components: {
fsNavbar,
},
};
</script>
components/fs-navbar.vue
<template>
<nav>...</nav>
</template>
<style scoped lang="scss">
</style>
<script>
import Vue from 'vue';
export default Vue.component('fs-navbar', {
// logic
});
</script>
This app causes an error:
vue.js?3de6:2574[Vue warn]: Failed to mount component: template or render function not defined. (found in component <fs-navbar>)
If I add fs-navbar template directly into app.vue's template everything is working as intended. Without router app is working as well.
I'm using vue-cli with this template(vuejs2)
Smilar problem, when I write:
let routes = [{
path: '/',
component: require('./components/member.vue')
}]
it failed:[Vue warn]: Failed to mount component: template or render function not defined.
add ".default", it works!
let routes = [{
path: '/',
component: require('./components/member.vue').default
}]
PS:"vue": "^2.5.2","vue-router": "^3.0.1""vue-loader": "^13.3.0",
https://github.com/vuejs/vue-loader/releases/tag/v13.0.0
Turns out, that Vue.component() return value isn't working with the router.
When changed:
export default Vue.component('component-name', {})
to:
export default {}
Everything is working fine.