Router in Vue not workin - html

I have tried a 100 times but my router is not working at all!
I cant just navigate or switch to different pages in my vue project. I followed all the steps given in the link https://www.thepolyglotdeveloper.com/2017/11/router-navigate-pages-vuejs-application/ too, but no change.
Here are my codes:
main.js
import Vue from 'vue'
import App from './App.vue'
import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
//import router from '../router'
//import VueRouter from 'vue-router'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
index.js
import Vue from 'vue'
import Router from 'vue-router'
import Page1 from '#/components/page1'
import Page2 from '#/components/page2'
Vue.use(Router)
export default new Router({
routes: [
{
path: "/",
redirect: {
name: "Page1"
}
},
{
path: '/page1',
name: 'Page1',
component: Page1
},
{
path: '/page2',
name: 'Page2',
component: Page2
}
]
})
Now here is an example of one of my page whos address i expect to be localhost:8080/page1 but its not coming..
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<router-link to="/page2">Navigate to Page2</router-link>
</div>
</template>
<script>
export default {
name: 'Page1',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
}
</script>
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
SOMEONE PLEASE TELL ME WHAT TO DO

Your main.js must look like:
import Vue from 'vue'
import App from './App.vue'
import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import router from '../router';
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
router,
}).$mount('#app')
Also in App.vue you must have <RouterView />:
<template>
<RouterView />
</template>
Source: https://router.vuejs.org/guide/#html

Related

Only in the context of a <Router> component error on import outside project root

I have two React projects.
Project "app" contains the main project.
Project "sb" contains a Storybook project.
The dependencies have been made the same, both projects are created with CRA.
app/
components/
SampleComp.tsx
sb/
components/
SampleComp.tsx
stories/
SampleComp.stories.tsx
Both SampleComp.tsx are exactly the same in code.
When I import SampleComp.tsx from the sb/components folder, it's working.
When I import SampleComp.tsx from the app/components folder, it's NOT working.
The latter fails with the following error in Storybook:
"useHref() may be used only in the context of a component."
In the stories, I wrap the component in the MemoryRouter.
SampleComp.tsx (both)
import React from "react";
import { Link } from "react-router-dom";
export function SampleComp() {
return (
<div>
Home page
<Link to="/test">Test</Link>
</div>
);
}
SampleComp.stories.tsx
import React from "react";
import { ComponentStory, ComponentMeta } from "#storybook/react";
// import { SampleComp } from "../../app/components/SampleComp"; // not working
import { SampleComp } from "../components/SampleComp"; // works!
import { MemoryRouter } from "react-router";
export default {
title: "SampleComp",
component: SampleComp,
parameters: {
layout: "fullscreen",
},
} as ComponentMeta<typeof SampleComp>;
const Template: ComponentStory<typeof SampleComp> = (args) => (
<MemoryRouter>
<SampleComp />
</MemoryRouter>
);
export const Default = Template.bind({});
Why doesn't it work the same?

How can I use vue-router-tab in Vue3?

I installed vue-router-tab. (npm i vue-router-tab -S) and configured.
main.js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import RouterTab from "vue-router-tab";
import "vue-router-tab/dist/lib/vue-router-tab.css";
const app = createApp(App);
app.use(RouterTab);
app.use(store);
app.use(router);
app.mount("#app");
router/index.js
import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";
import { RouterTabRoutes } from "vue-router-tab";
import Frame from "../components/layout/Frame.vue";
const routes = [
{
path: "/",
component: Frame,
children: [
...RouterTabRoutes,
{
path: "/",
name: "Home",
component: Home,
meta: {
title: "Home",
},
},
{
path: "/about",
name: "About",
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue"),
meta: {
title: "About",
},
},
],
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
components/layout/Frame.vue
<template>
<router-tab />
</template>
<script>
export default {
name: "Frame",
setup() {},
};
</script>
App.vue
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</template>
<script>
export default {};
</script>
npm run serve throws error.
It works fine in vue2, but in vue3, an error occurs saying the tabs property is not defined.
How can I use vue-router-tab in Vue3? help me please.

React won't render my components using router

I am very new to react and trying to work on my first website.
I have tried to seek my problem online, I've encountered similar questions to mine but could not figure out my exact problem.
My layout of components are in a scroll down style (portfolio), when I try route for example to my contact component it wont render unless I refresh my page. also instead of scrolling down to component it will pop up at the top .(Hope I am clear)
My App Function
import { useState } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import './App.css';
import Contact from './Components/Contact/Contact';
import Form from './Components/FormArea/Form/form';
import Introdoction from './Components/Introdoction/Introdoction';
import NavBar from './Components/NavBar/NavBar';
import NavigationBar from './Components/NavigationBarHeader/NavigationBar/NavigationBar';
import Portfolio from './Components/Portfolio/Portfolio';
import Routing from './Components/Routing/Routing';
import Skills from './Components/Skills/Skills';
function App() {
return (
<BrowserRouter>
<Switch>
<div className="App">
<NavigationBar/>
<section className="section">
<Route path="/contact" component={Contact} exact/>
<Introdoction/>
<Portfolio/>
<Skills/>
{/* <Contact/> */}
<Form/>
</section>
</div>
</Switch>
</BrowserRouter>
);
}
export default App;
I am trying to configure "Contact" component for this example.
My Menu/Navbar Component
import { Component, MouseEventHandler } from "react";
import {MenuItems} from "../MenuItems/MenuItems";
import "./NavigationBar.css";
import icon from '../../../Assets/icon.png'
import {Button} from "../Button/Button";
import { NavLink, Redirect, Route, Switch, useHistory } from "react-router-dom";
import Contact from "../../Contact/Contact";
class NavigationBar extends Component {
state = {clicked : false}
handleClick = () => {
this.setState ( { clicked: !this.state.clicked } );
};
public render(): JSX.Element {
return (
<nav className="NavbarItems ">
<img className="navbar-logo"src={icon } />
<div className="menu-icon" onClick={this.handleClick}>
<i className={this.state.clicked ? 'fas fa-times' : 'fas times'}></i>
</div>
<ul className={this.state.clicked ? 'nav-menu active' : 'nav-menu'}>
{MenuItems.map((item,index) => {
return (
<li key={index}>
<NavLink to={item.url} className={item.cName} >{item.title} </NavLink>
</li>
)
})}
</ul>
<Button>Sign up</Button>
</nav>
);
}
}
export default NavigationBar;
ItemMenu Component
import { NavLink } from "react-router-dom";
import "./MenuItems.css";
export const MenuItems = [
{
title: 'Home',
url: '/Home',
cName: 'nav-links'
},
{
title: 'Introduction',
url: '/introduction',
cName: 'nav-links'
},
{
title: 'Skills',
url: '/skills',
cName: 'nav-links'
},
{
title: 'Projects',
url: '/projects',
cName: 'nav-links'
},
{
title: 'Contact',
url: '/contact',
cName: 'nav-links'
},
];
I could add more information if needed. I hope my question is clear on what my problem is.
Thanks.
If I understood your question correctly, you want one single page, with everything below each other, and when you press a link, it scrolls you down to that place. In that case I would use:
<Contact id="contact" />
react-router creates new sub pages, which you don't want (if I understood you correctly)

How load html template in vuejs

I use vue.js and vue-router.js.
I added both of files to a html page
This is my component for load template...
const Dashboard = {template: "<strong>"}
But I want load html page dynamically and with HTTP URL.
const Dashboard = {template: "How load html page with url(http)"}
Can anyone guide me?
you could define a component similar to this
Vue.component('dynamic-component', {
props: {
contentURL: String,
},
template: `<div v-html='inner_html'></div>`,
computed: {
inner_html() {
return // http call to get html value utilizing this.contentURL
},
},
});
then from the router
{
path: '/path/option-a',
components: {
DynamicComponent
},
props: {
contentURL: `https://some-resource/option-a`
}
},
{
path: '/path/option-b',
components: {
DynamicComponent
},
props: {
contentURL: `https://some-resource/option-b`
}
}
For creating layers, you can create vue component and use slot
Layout.vue
<template>
Header
AnyComponents
<slot />
Footer
</template>
and in your page component you should import your layout and wrap
MainPage.vue
<template>
<MainLayout>
Here is your conntent of page or router
<router-view />
</MainLayout>
</template>
<script>
import MainLayout from 'layout.vue';
export default {
components: {
MainLayout
}
}
</script>
And now for render your page you should use your page in router
example of router.js
import Vue from 'vue';
import Router from 'vue-router'
import MainPage from 'MainPage.vue';
Vue.use(Router)
export default new Router({
routes: [{
path: '/',
component: MainPage,
}]
})
If you want to insert html to your page, use v-html
<div class="content" v-html="dashboard.template">
</div>

Using Jest to test a Link from react-router v4

I'm using jest to test a component with a <Link> from react-router v4.
I get a warning that <Link /> requires the context from a react-router <Router /> component.
How can I mock or provide a router context in my test? (Basically how do I resolve this warning?)
Link.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import { Link } from 'react-router-dom';
test('Link matches snapshot', () => {
const component = renderer.create(
<Link to="#" />
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
The warning when the test is run:
Warning: Failed context type: The context `router` is marked
as required in `Link`, but its value is `undefined`.
You can wrap your component in the test with the StaticRouter to get the router context into your component:
import React from 'react';
import renderer from 'react-test-renderer';
import { Link } from 'react-router-dom';
import { StaticRouter } from 'react-router'
test('Link matches snapshot', () => {
const component = renderer.create(
<StaticRouter location="someLocation" context={context}>
<Link to="#" />
</StaticRouter>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
Have a look at the react router docs about testing
I had the same issue and using StaticRouter would still require the context which needed more configuration to have it available in my test, so I ended up using the MemoryRouter which worked very well and without any issues.
import React from 'react';
import renderer from 'react-test-renderer';
import { MemoryRouter } from 'react-router-dom';
// SampleComponent imports Link internally
import SampleComponent from '../SampleComponent';
describe('SampleComponent', () => {
test('should render', () => {
const component = renderer
.create(
<MemoryRouter>
<SampleComponent />
</MemoryRouter>
)
.toJSON();
expect(component).toMatchSnapshot();
});
});
The answer of #Mahdi worked for me! In 2023 if you want to test a component that includes <Link> or <NavLink>, we just need to wrap it with the <MemoryRouter> in the test file:
// App.test.js
import { render, screen } from "#testing-library/react";
import MyComponent from "./components/MyComponent";
import { MemoryRouter } from "react-router-dom"; // <-- Import MemoryRouter
test("My test description", () => {
render(
<MemoryRouter> // <-- Wrap!
<MyComponent />
</MemoryRouter>
);
});
my test like this:
import * as React from 'react'
import DataBaseAccout from '../database-account/database-account.component'
import { mount } from 'enzyme'
import { expect } from 'chai'
import { createStore } from 'redux'
import reducers from '../../../reducer/reducer'
import { MemoryRouter } from 'react-router'
let store = createStore(reducers)
describe('mount database-account', () => {
let wrapper
beforeEach(() => {
wrapper = mount(
< MemoryRouter >
<DataBaseAccout store={store} />
</MemoryRouter >
)
})
afterEach(() => {
wrapper.unmount()
wrapper = null
})
})
but I don't konw why MemoryRouter can solve this。
Above solutions have a common default defact:
Can't access your component's instance! Because the MemoryRouter or StaticRouter component wrapped your component.
So the best to solve this problem is mock a router context, code as follows:
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
describe('YourComponent', () => {
test('test component with react router', () => {
// mock react-router context to avoid violation error
const context = {
childContextTypes: {
router: () => void 0,
},
context: {
router: {
history: createMemoryHistory(),
route: {
location: {
hash: '',
pathname: '',
search: '',
state: '',
},
match: { params: {}, isExact: false, path: '', url: '' },
}
}
}
};
// mount component with router context and get component's instance
const wrapper = mount(<YourComponent/>, context);
// access your component as you wish
console.log(wrapper.props(), wrapper.state())
});
beforeAll(() => {
configure({ adapter: new Adapter() });
});
});