Vue / vue-router scoping - javascript

import ExpenseView from './path'
import template from './path'
const MainComponent = new Vue({
el: '#app',
data: {
expense: [{ description: 'expense description', amount: 14.99, _id: 'l;dkfjg;ladfjg;klafjg;l' }],
},
router: new VueRouter({
routes: [
{ path: '/dash', component: ExpenseView, props: { default: true, expenses: MainComponent.expense } },
]
}),
template,
created() {...},
methods: {...},
computed: {...}
})
My goal is to have the router listen to the data in MainComponent but there are scoping issues - MainComponent is not defined.
Is there a way to get the router listening to the data in MainComponent with the way this is structured?

You can see the following example
//you can try the following code
//index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
import RSSFeed from '#/components/RSSFeed.vue'
export default new Router({
routes: [
{
path: '/rss-feed',
name: 'RSSFeed',
component: RSSFeed,
props: { authorName: 'Robert' }
},
]
})
//RSSFeed.vue
<template>
<ol id="feed">
{{authorName}}
</ol>
</template>
<script>
import Post from './Post'
export default {
props: ['authorName'],
data () {
return {
items: [
{
"title":"Vuejs Nodejs",
"pubDate":"20-07-2018",
"description":"Leading vuejs nodejs",
"link":"https://hoanguyenit.com"
}
],
errors: []
}
}
}
</script>
Example
//in router
const router = new VueRouter({
routes: [
{ path: 'YOUR__PATH', component: Home, props: { authorName: 'Robert' } }
]
})
//in Home.vue
//And inside the <Home /> component,
var Home = Vue.extend({
props: ['authorName'],
template: '<p>Hey, {{ authorName }}</p>'
});

Related

VueJS | How can i get url parameters in vue.js?

Hi I'm making my own websites. and i'm newbie vue.js
I'm trying to get parameters to url.
I've been trying to any method. but not works.
Here is a url. -> example.com:8080/login
in this page, there's a button to register.
All i want is when i give url parameter(example.com:8080/login?id=hello&pw=1234), in login.vue, insert value -> user_id = hello, user_pw = 1234 and going back to exapmle.com:/8080
i'm trying to using vue.router. but it not works.
the error is
javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup!
and this is /router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '../views/Main.vue'
import Login from '../views/Login.vue'
import Intro from '../views/Intro.vue'
import Info from '../views/Info.vue'
import Setting from '../views/Setting.vue'
import store from '../store'
import user_id from '../views/Login.vue'
import user_pw from '../views/Login.vue'
Vue.use(VueRouter)
const routes = [{
path: '/',
redirect: '/main',
},
{
path: '/login',
name: 'login',
component: Login,
},
{
path: '/signup',
name: '/signup',
component: SignUp
},
{
path: '/main',
component: Main,
beforeEnter(to, from, next) {
if (store.state.accessToken) {
next();
} else {
next('/login');
}
},
children: [{
path: '',
name: 'intro',
component: Intro,
},
{
path: '/info',
name: 'info',
component: Info,
},
{
path: '/setting',
name: 'setting',
component: Setting,
},
]
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: Login
});
var myApp = new Vue({
router,
el: '#app',
mounted: function() {
let parameters;
parameters = this.$route.query
console.log(parameters)
user_id = this.$route.query.id
user_pw = this.$route.query.pw
}
})
export default router
and this is part of login.vue
export default {
name: "test",
function() {
return {
id: "",
pw: "",
};
},
methods: {
test() {
axios.post("/login", {
id: this.userId,
pw: this.password
})
.then(function(response) {
if(response.data.code === 200) {
}
})
},
mounted : function() {
this.load();
}
}
i don't know what is wrong in my code.
my explain is too bad. sorry. but i'm trying to do my best
You are assigning routes to the Login component.
Replace
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: Login
});
with
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
});
"Hello world" example (Maybe it will be helpful). Click on the link to get utm_source:
const User = {
template: `<div><b>User:</b> {{ this.$route.params.id }} | <b>utm_source:</b>
{{this.$router.currentRoute.query['utm_source']}}</div>`
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
const app = new Vue({ router }).$mount('#app')
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<nav>
<router-link to="/user/foo?utm_source=facebook">Click her to see the utm_source=facebook of /user/foo?utm_source=facebook</router-link>
</nav>
<router-view></router-view>
</div>

Trying to make a VueJS API call with axios to get json in a component named prijzen

I am new to Vue and am trying to load in json data from a REST API called JSON placeholder. I get the error:
"Uncaught ReferenceError: Prijzen is not defined
at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/layout/Prijzen.vue?vue&type=script&lang=js&:16)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/layout/Prijzen.vue?"
So after i got this i tried looking at index.js but prijzen is added there.. the code looks like this:
import Vue from 'vue'
import Router from 'vue-router'
// Containers
const TheContainer = () => import('#/containers/TheContainer')
// Views
const Dashboard = () => import('#/views/Dashboard')
const Prijzen = () => import('#/views/layout/Prijzen')
const Login = () => import('#/views/layout/Login')
Vue.use(Router)
export default new Router({
mode: 'hash', // https://router.vuejs.org/api/#mode
linkActiveClass: 'open active',
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: '/',
redirect: '/dashboard',
name: 'Home',
component: TheContainer,
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: Dashboard
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/layout/prijzen',
name: 'Prijzen',
component: Prijzen
}
]
},
]
})
So prijzen is fine here. At least it looks fine to me. This is how the prijzen component looks:
<template>
<div id="Prijzen">
{{ prijs }}
</div>
</template>
<script>
import axios from 'axios';
import PrijsItem from './PrijsItem.vue';
export default {
name: 'Prijzen',
components: {
PrijsItem
},
props: ["PrijsItem"]
}
</script>
I have used {{ prijs }} in the template and in my main.js file it is being mentioned with my axios get request as you can see here:
import 'core-js/stable'
import Vue from 'vue'
import CoreuiVue from '#coreui/vue/src'
import App from './App'
import router from './router/index'
import { iconsSet as icons } from './assets/icons/icons.js'
import store from './store'
Vue.use(CoreuiVue)
new Vue({
el: '#app',
router,
store,
//CIcon component documentation: https://coreui.io/vue/docs/components/icon
icons,
template: '<App/>',
components: {
App,
Prijzen
},
new:({
let: '#Prijzen',
data () {
return {
prijs: null
}
},
mounted () {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(response => (this.prijs = response))
}
})
})
Is the Prijzen.vue file definitely in the views/layout directory? That error looks like it might be caused by not being able to find the file where you've told it to look.
A different issue:
{{ prijs }}
Is in the template, but prijs is not defined. Also PrijsItem component has been imported but not used which will sometimes throw linting errors.

Vue Router - Paths being concatenated multiple times

I am facing problems with the Vue Router and I have no idea what is causing this...
When my application loads it inserts the page path twice.
Example:
If I access the path http://localhost:8080/painel it will be shown in the browser the following path: http://localhost:8080/painel/painel
If I refresh the page the path will be added one more time, going like this: http://localhost:8080/painel/painel/painel
MY files:
/src/main.js
import Vue from 'vue'
import localforage from 'localforage'
import Notifications from 'vue-notification'
import App from './App'
import store from './store'
import router from './router'
import bus from './support/bus'
import http from './support/http'
Vue.config.productionTip = true
window._ = require('lodash')
localforage.config({
driver: localforage.LOCALSTORAGE,
storeName: 'invenio-center'
})
store.dispatch('auth/setToken').then(() => {
store.dispatch('auth/fetchSystemData').catch(() => {
store.dispatch('auth/clearAuth')
})
}).catch(() => {
store.dispatch('auth/clearAuth')
})
Vue.use(Notifications)
Vue.use(bus)
Vue.use(http)
new Vue({
el: '#app',
router,
store,
components: {App},
template: '<App/>'
})
/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import Login from '../pages/Login'
import Panel from '../pages/Panel'
import PanelIndex from '../pages/panel/Index'
Vue.use(Router)
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'login',
component: Login,
meta: {
visitor: true
}
},
{
path: 'painel',
component: Panel,
meta: {
auth: true
},
children: [
{
path: '/',
name: 'panel.index',
component: PanelIndex
},
{
path: 'idr',
name: 'panel.idr',
component: PanelIndex
}
]
},
{
path: "*",
redirect: {
name: 'panel.index'
},
component: PanelIndex
}
]
})
router.beforeEach(
(to, from, next) => {
store.dispatch('auth/setToken').then(() => {
if(to.meta.visitor){
next({
name: 'panel.index'
});
return;
}
next();
}).catch(() => {
if(to.meta.auth){
next({
name: 'login'
});
return;
}
next();
})
}
)
export default router
/src/pages/Panel.vue
<template>
<div class="panel-container">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Panel',
data() {
return {
}
}
}
</script>
<style lang="scss" scoped>
.panel-container {
}
</style>
/src/pages/panel/Index.vue
<template>
<div class="index-container">index</div>
</template>
<script>
export default {
name: 'PanelIndex',
data() {
return {
}
}
}
</script>
<style lang="scss" scoped>
.index-container {
}
</style>
try this, add / before path: '/painel', and do that for other components.
/ is used to distinct from relative path.

Trouble getting data from root Vue instance with vue-router

I load all of my data in the root Vue instance and im trying to access them in my router.
How can I access the data in my root instance within my router? All the this.a.app or this.app answers i found online weren’t the solution.
Router.js:
import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/login'
import Container from '../components/container'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [{
path: '/login',
name: 'Login',
component: Login,
props: { test: **<data from my Vue root instance>** }
},
{
path: '/products',
name: 'Container',
component: Container,
children: [{
path: 'flavor',
component: Login
},
{
path: 'storage',
component: Login
},
{
path: 'network',
component: Login
}
]
}
]
})
Main.js:
import router from './router’
var vm = new Vue({
el: ‘#app’,
router,
template: ‘’,
components: {
App
},
data() {
return {
modal: ‘’
I would avoid sharing the data using the router instance.
I personally like to have a store file, which contains data I want to share between my components.
export default {
state: {
counter: 0
}
}
And in your component you can import the file:
import store from '../store'
export default {
data () {
return {
sharedState: store.state
}
}
}
Changes to sharedState will also be passed to other components.
Source: https://skyronic.com/2016/01/03/vuex-basics-tutorial / Solution 2

VUEJS vue-router access router from nested routes

I have problem to access route object from nested views. Here is the simplified code:
main.js
import Vuetify from 'vuetify'
import VueRouter from 'vue-router'
import Vuetify from 'vuetify'
Vue.use(VueRouter)
Vue.use(Vuetify)
const router = new VueRouter({
routes : [
{path : '/contacts', component: Contacts,
children: [
{
path: ':id',
component: ContactDetails
}
]
},
],
mode: 'history'
})
new Vue({
el: '#app',
render: h => h(App),
router
})
ContactDetails.vue
<template>
<v-btn icon dark class="mr-3" #click.native="editContact">
<v-icon>edit</v-icon>
</v-btn>
</template>
<script>
export default {
data : () => ({
}),
methods: {
editContact: ()=>{
console.log('edit contact');
this.$router.go(-1) //this gives an error
}
},
}
</script>
It says "router is undefined", when I use
this.$router.go(-1)
from main routes (aka /contacts), it works. I tried all of the below code on the child:
router.go(-1)
$router.go(-1)
this.$router.go(-1)
this.router.go(-1)
this.$parent.$router.go(-1)
None of them works. Is there a way to reach to router object from nested routes? Or should I emit an event to parent and change view from there?
I have found an error in your code - it's in ()=>{...} function :)
Using an arrow function you are addressing ContactDetails-component this (object) and it does not contain any $router indeed. After you change an arrow function to function() {} your code will work as expected, because Vue rebinded to its instance where the $router is declared.
Now, lets look at this working copy (codepen) of your code:
Vue.use(VueRouter)
let ContactDetails = {
mounted() {
console.log('ContactDetails mounted...');
},
methods: {
editContact: function() {
console.log('edit contact');
this.$router.go(-1) //this DOES NOT give an error ANYMORE
}
},
template: `<button #click="editContact">edit</button>`,
}
let Contacts = {
components: {ContactDetails},
mounted() {
console.log('Contacts mounted...');
},
template: `Contacts... <ContactDetails></ContactDetails>`,
};
const router = new VueRouter({
mode: 'hash',
routes : [{
path : '/contacts',
component: Contacts,
children: [{
path: 'id',
component: ContactDetails
}]
}],
});
const vm = new Vue({
el: '#app',
components: {
Contacts,
ContactDetails,
},
router
});
vm.$router.push("/contacts/id");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<router-view></router-view>
</div>

Categories

Resources