Component prop isn't reactive after initial router push (VueJS) - javascript

I have some views/components; Home, ScrapeResults, and Search. To help y'all follow what is going on, here are some snippets of code that are relevant to my issue.
Snippet of App.vue
<template>
<v-app-bar>
<Search #selected_card="scrape"/>
</v-app-bar>
<v-content>
<v-container fluid style="width: 80%;">
<router-view :card="card"></router-view> //card prop is in ScrapeResults.vue
</v-container>
</v-content>
</template>
<script>
data() {
return {
card: {}
}
}
methods: {
scrape(card) { //card parameter value is from $emit event from Search
if(this.$router.currentRoute.name != 'scrape-results') {
this.$router.push({name: 'scrape-results', params: { card: card } });
}
else {
this.card = card;
console.log(this.card)
}
}
}
</script>
Snippet of Home.vue
<template>
<div id="home">
<h1>Home</h1>
<Search id="search" #selected_card="scrape"/>
</div>
</template>
<script>
methods: {
scrape(card) { //card parameter value is from $emit event from Search
this.$router.push({ name: 'scrape-results', params: { card: card } });
}
}
</script>
Snippet of ScrapeResults:
<template>
<div id="home">
<h1>Scrape Results</h1>
<p> {{card.name}} - {{card.set_name}} </p>
<v-img :src="card.img_url"></v-img>
</div>
</template>
<script>
...... //irrelevant stuff
props: {
card: Object
},
watch: {
card() {
console.log(this.card)
}
}
</script>
Paths within the app:
/ (Home)
/scrape-results (ScrapeResults)
So how the app work is the user will search for a card (Object) and select from a rendered list. Once the user selects a card from the rendered list, then the user is redirected to the Scrape Results view. All of that works fine when done from Home.vue.
My issue: If the user accessed Scrape Results from Home.vue, and while still on Scrape Results view, if the user were to search for another card via the Search component that is mounted (in the app bar) in App.vue, then the card prop in ScrapeResults.vue doesn't update. The weird thing is that if I manually navigate to Scrape Results by entering /scrape-results in the address bar, search for a card via the Search component in the app bar, then the card prop updates. The card prop will only update if I manually access /scrape-results and then search for a card.
I know all of that sounds confusing, so here's a clip I recorded to that demonstrates what my issue is. Link: https://www.youtube.com/watch?v=aO9qSTa9CCk&feature=youtu.be&hd=1
EDIT: Route definition below
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '#/views/Home'
import ScrapeResults from '#/views/ScrapeResults'
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/scrape-results',
name: 'scrape-results',
component: ScrapeResults,
props: true
}
]
});
export default router;

So, instead of trying to make passing a prop to router-view work, I just ended up changing the ScrapeResults path in my router.js to /scrape-results/:card_set/:card_name; original was just /scrape-results. I then just pushed extra params in $router.push
this.$router.push({name: 'scrape-results', params: { card: card, card_set: card.set_name, card_name: card.name } });

Related

How to throw data to main App.vue from views? [duplicate]

I have two components:
App.vue
Sidekick.vue
In my App.vue component, I have a property that I would like to access from Sidekick.vue
App.vue
<template>
<div id="app">
<p>{{ myData }}</p>
<div class="sidebar">
<router-view/> // our sidekick component is shown here
</div>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
myData: 'is just this string'
}
}
}
</script>
Sidekick.vue
<template>
<div class="sidekick">
{{ myData }}
</div>
</template>
<script>
export default {
name: 'Sidekick'
}
</script>
I would like access to myData (which is declared in App.vue) from Sidekick.vue
I have tried importing App.vue from within Sidekick.vue by doing something like:
Sidekick.vue (incorrect attempt)
<script>
import App from '#/App'
export default {
name: 'Sidekick',
data () {
return {
myData: App.myData
}
}
}
</script>
I have read about props - but have only seen references to child / parent components. In my case, Sidekick.vue is shown in a div inside App.vue (not sure if this makes it a "child"). Do I need to give access of myData to <router-view/> somehow?
UPDATE: (to show relationship between App.vue and Sidekick.vue
index.js (router file)
import Vue from 'vue'
import Router from 'vue-router'
import Sidekick from '#/components/Sidekick',
import FakeComponent from '#/components/FakeComponent'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
redirect: '/fakecomponent'
},
{
path: '/sidekick',
name: 'Sidekick',
component: Sidekick
},
{
path: '/fakecomponent',
name: 'FakeComponent',
component: FakeComponent
}
]
})
export default router
Sidekick.vue gets rendered when we hit /sidekick
Just keep in mind, the rule of thumb is using props to pass data in a one-way flow
props down, events up.
https://v2.vuejs.org/v2/guide/components.html#Composing-Components
Quick solution:
Global event bus to post messages between your <App/> and <Sidekick/> components.
https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
Long term solution:
Use a state management library like vuex to better encapsulates data in one place (a global store) and subscribe it from your components tree using import { mapState, mapMutations } from 'vuex'
When you have parent-child communication, the best and recommended
option is to use props and events. Read more in Vue docs
When want to have shared state between many components the best and
recommended way is to use Vuex.
If you want to use simple data sharing you can use Vue observable.
Simple example: Say that you have a game and you want the errors to be accessible by many components. (components can access it and manipulate it).
errors.js
import Vue from "vue";
export const errors = Vue.observable({ count: 0 });
Component1.vue
import { errors } from 'path-of-errors.js'
export default {
computed: {
errors () {
get () { return errors.count },
set (val) { errors.count = val }
}
}
}
In Component1 the errors.count is reactive. So if as a template you have:
<template>
<div>
Errors: {{ errors }}
<button #click="errors++">Increase</button>
</div>
</template>
While you click the Increase button, you will see the errors increasing.
As you might expect, when you import the errors.js in another component, then both components can participate on manipulating the errors.count.
Note: Even though you might use the Vue.observable API for simple data sharing you should be aware that this is a very powerful API. For example read Using Vue Observables as a State Store
App.vue:
<router-view pass_data='myData'/>
Sidekick.vue:
export default {
name: "Sidekick",
props: ["pass_data"],
created() {
alert("pass_data: "+this.pass_data)
}
}
If App.js(Parent) and Sidekick(Child)
App.js
in Template
In script
import Sidekick from './Sidekick.vue:
Sidekick.vue
props: ['myData']
now you can access myData anywhere in sidekick.
In template myData and
in scripts this.myData

Vue Dynamic Layouts mounting router-view component twice

I setup my Vue project to use dynamic layouts - that is, layouts that persist from page to page, assuming the layout for the new page is the same as the last page. My problem is that when I go to a route with a different layout, the router-link component gets created and destroyed, then created again, which is causing me some issues. My setup is as follows:
App.vue
<template>
<component :is="layout">
<router-view :layout.sync="layout" />
</component>
</template>
<script>
import LayoutPortal from '#/layouts/LayoutPortal';
import LayoutOffline from '#/layouts/LayoutOffline';
import LayoutDefault from '#/layouts/LayoutDefault';
export default {
name: 'App',
components: {
LayoutPortal,
LayoutOffline,
LayoutDefault,
},
...
Some router-view Component
<template>
...
</template>
<script>
import LayoutDefault from '#/layouts/LayoutDefault';
export default {
...
created() {
this.$emit('update:layout', LayoutDefault);
},
}
</script>
Layout Default
<template>
<div class="wrapper">
<slot />
</div>
</template>
<script>
export default {
name: 'layout-default',
};
</script>
tldr;
If you setup your project using dynamic layouts, following any of a number of tutorials out there online, when you navigate to a route with a different layout than the last page, the new router-view component gets created, destroyed, then created again. This causes issues like doubling up on mounted() calls and more.
I ultimately went with nested (child) routes (https://router.vuejs.org/guide/essentials/nested-routes.html):
{
path: '/portal',
component: LayoutPortal,
beforeEnter(to, from, next) {
if (!store.getters.auth) {
next('/login');
return;
}
next();
},
children: [
{
path: 'home',
name: 'portal-home',
component: PortalHome,
},
{
path: 'about',
name: 'portal-about',
component: PortalAbout,
},
...
In this way I can load up the layout as the parent route, separate beforeEnter logic into separate route groups, and avoid the problem where going to a page with a new layout loads a component twice.

VueJS passing router to child component

How Can I pass router to my child component.
I have this as my router
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
export default function () {
const Router = new VueRouter({
mode: 'history',
routes : [
{
path: '/',
beforeEnter: ifAuthenticated,
component: () => {
return import('./../container/Index.vue')
}
},
{
path: '/login',
beforeEnter: ifNotAuthenticated,
component: () => {
return import('./../container/logn.vue')
}
}
],
})
return Router
}
Now my "/" (index.vue) route have a component Navbar and the Navbar have a logout button which logs out the user and redirect them to login page
Consider this to be my index.vue (with what I have done)
<template>
<q-layout>
<Navbar :thisInfo="routerAndStore"/>
</q-layout>
</template>
<script>
import Navbar from "./../components/navbar.vue";
export default {
name: "PageIndex",
components: {
Navbar
},
data() {
return {
routerAndStore: this
};
}
};
</script>
And then in my navbar.vue I have done something like this
<template>
<div class="nav-pages-main">
<a #click="logoutUser">
<h5>Logout</h5>
</a>
</div>
</template>
<script>
export default {
name: "navbar",
methods: {
logoutUser: () => {
return this.thisInfo.$store.dispatch("GOOGLE_PROFILE_LOGOUT").then(() => {
this.$router.push("/login");
});
}
},
props: {
thisInfo: {
type: Object
}
}
};
</script>
but this doesn't seem to be working (this is coming out to be undefined), So if someone can help me figure out how we can pass this to our child component
Please refer to Vue-Router official documentation here
Basically, in their use case, the main component (index.vue) take a router as argument and provide <router-view> in its template as placeholder for component that would be rendered based on the current route.
In your code, I see that you use it the other way around using router to render the main component.
routes : [
{
path: '/',
beforeEnter: ifAuthenticated,
component: () => {
return import('./../container/Index.vue')
}
},
...
]
Could you try it again using the right way described in the documentation and tell me the result?
Edit: According to the App.vue that you posted (assuming it's the app entry point) then you should provide router to the App component.
<template>
<div id="q-app"> <router-view/> </div>
</template>
<script>
import router from '/path/to/your/router';
export default { name: "App", router };
</script>
<style>
</style>
The full code for this can be found at Vue-Router example

Vuejs Share Data Between Components

I have two components:
App.vue
Sidekick.vue
In my App.vue component, I have a property that I would like to access from Sidekick.vue
App.vue
<template>
<div id="app">
<p>{{ myData }}</p>
<div class="sidebar">
<router-view/> // our sidekick component is shown here
</div>
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
myData: 'is just this string'
}
}
}
</script>
Sidekick.vue
<template>
<div class="sidekick">
{{ myData }}
</div>
</template>
<script>
export default {
name: 'Sidekick'
}
</script>
I would like access to myData (which is declared in App.vue) from Sidekick.vue
I have tried importing App.vue from within Sidekick.vue by doing something like:
Sidekick.vue (incorrect attempt)
<script>
import App from '#/App'
export default {
name: 'Sidekick',
data () {
return {
myData: App.myData
}
}
}
</script>
I have read about props - but have only seen references to child / parent components. In my case, Sidekick.vue is shown in a div inside App.vue (not sure if this makes it a "child"). Do I need to give access of myData to <router-view/> somehow?
UPDATE: (to show relationship between App.vue and Sidekick.vue
index.js (router file)
import Vue from 'vue'
import Router from 'vue-router'
import Sidekick from '#/components/Sidekick',
import FakeComponent from '#/components/FakeComponent'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
redirect: '/fakecomponent'
},
{
path: '/sidekick',
name: 'Sidekick',
component: Sidekick
},
{
path: '/fakecomponent',
name: 'FakeComponent',
component: FakeComponent
}
]
})
export default router
Sidekick.vue gets rendered when we hit /sidekick
Just keep in mind, the rule of thumb is using props to pass data in a one-way flow
props down, events up.
https://v2.vuejs.org/v2/guide/components.html#Composing-Components
Quick solution:
Global event bus to post messages between your <App/> and <Sidekick/> components.
https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
Long term solution:
Use a state management library like vuex to better encapsulates data in one place (a global store) and subscribe it from your components tree using import { mapState, mapMutations } from 'vuex'
When you have parent-child communication, the best and recommended
option is to use props and events. Read more in Vue docs
When want to have shared state between many components the best and
recommended way is to use Vuex.
If you want to use simple data sharing you can use Vue observable.
Simple example: Say that you have a game and you want the errors to be accessible by many components. (components can access it and manipulate it).
errors.js
import Vue from "vue";
export const errors = Vue.observable({ count: 0 });
Component1.vue
import { errors } from 'path-of-errors.js'
export default {
computed: {
errors () {
get () { return errors.count },
set (val) { errors.count = val }
}
}
}
In Component1 the errors.count is reactive. So if as a template you have:
<template>
<div>
Errors: {{ errors }}
<button #click="errors++">Increase</button>
</div>
</template>
While you click the Increase button, you will see the errors increasing.
As you might expect, when you import the errors.js in another component, then both components can participate on manipulating the errors.count.
Note: Even though you might use the Vue.observable API for simple data sharing you should be aware that this is a very powerful API. For example read Using Vue Observables as a State Store
App.vue:
<router-view pass_data='myData'/>
Sidekick.vue:
export default {
name: "Sidekick",
props: ["pass_data"],
created() {
alert("pass_data: "+this.pass_data)
}
}
If App.js(Parent) and Sidekick(Child)
App.js
in Template
In script
import Sidekick from './Sidekick.vue:
Sidekick.vue
props: ['myData']
now you can access myData anywhere in sidekick.
In template myData and
in scripts this.myData

Eventbus in Vue.js isn't updating my component

I have two components and I want to display what the user enters in one on the other component. I don't really want to use a state manager like vuex because it's probably a bit overkill as it's a small application
this is my main.js:
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import { routes }from './routes';
export const EventBus = new Vue();
Vue.use(VueRouter);
const router = new VueRouter({
routes,
mode: 'history'
});
new Vue({
el: '#app',
router,
render: h => h(App)
})
Component that emits the event called addHtml.vue
<template>
<div>
<h1>Add HTML</h1>
<hr>
<button #click="navigateToHome" class="btn btn-primary">Go to Library</button>
<hr>
Title <input type="text" v-model="title">
<button #click="emitGlobalClickEvent()">Press me</button>
</div>
</template>
<script>
import { EventBus } from '../../main.js'
export default {
data: function () {
return {
title: ''
}
},
methods: {
navigateToHome() {
this.$router.push('/');
},
emitGlobalClickEvent() {
console.log(this.title);
EventBus.$emit('titleChanged', this.title);
}
}
}
</script>
the file that listens for the event thats emitted and to display what was entered on the other component:
<template>
<div>
<h1>Existing Items</h1>
<hr>
<p>{{ test }}</p>
</div>
</template>
<script>
import { EventBus } from '../main.js';
export default {
data: function () {
return {
test: ''
}
},
created() {
EventBus.$on('titleChanged', (data) => {
console.log('in here!',data);
this.test = data;
});
}
}
</script>
the console.log('in here!',data); inside the listener gets printed out to the console so I know it's picking it up however {{ test }} doesn't get updated to what the user enters when I click back onto the component to view if it was updated, it just remains blank? Any Ideas?
If you are using vue-router to display the secound component. The reason might be that you just see a new instance of that component everytime and the value of test will be reseted when the component is destroyed. You can bind it to a (global) variable to persist test: window.yourApp.test. Maybe webpack will mourn but it is possible. Even eslint has an ignore comment for such cases.
It is like Reiner said, because the component gets destroyed once you switch pages. Try wrapping your router-view inside a keep-alive:
<keep-alive>
<router-view><router-view>
</keep-alive>
Also. If you want to keep the state of just one specific component / page you can use the include tag:
<keep-alive include='name of component'>
<router-view></router-view>
</keep-alive>

Categories

Resources