trigger method in parent from child nested in router in Quasar (vue) - vue.js

I got this structure with nested routes in my router using Quasar framework (vue 3):
const routes = [
{
path: "/",
component: () => import("layouts/myLayout.vue"),
children: [
{
path: "",
component: () => import("pages/Main.vue"),
children: [
{
path: "",
component: () => import("components/Sub.vue")
}
]
}
]
}
I know I can use $emit in my child to pass to parent like this:
MyChild:
this.$emit("myEvent", "hello world");
MyParent:
<MyChild #myEvent="updateMyEvent" />
However I want to trigger an event in parent without rendering MyChild once again in the parent since it is already displayed through the router ... So I am looking for a way of accessing the parents method more directly so to speak.
What is the correct implementation of doing this in vue 3?
UPDATE:
my method in child for updating vuex:
this.updateValue(JSON.parse(JSON.stringify(myValue)));
Store.js
vuex:
const state = {
value: 0
};
const actions = {
updateValue({ commit }, payload) {
commit("updateMyValue", payload);
},
const mutations = {
updateMyValue(state, payload) {
state.myValue = payload;
},
};
const getters = {
getValue: state => {
return state.value;
},
I actually ended up with a watcher on my getter in my parent:
computed: {
...mapGetters("store", ["getValue"]) // module and name of the getter
},
watch: {
getValue(val) {
console.log("MY VALUE: " , val);
}

In the child parent component define a computed property called stateValue that's based on the store state value and then watch it to trigger that event :
computed:{
stateValue(){
return this.$store.state.value;
}
},
watch:{
stateValue(val){
this.updateMyEvent()// trigger the method
}
}

Related

Vuex mapState based on route and route parameters

I have a works component I use different pages on my app and I am trying to load the state based on the route and route parameters.
In my App.vue file I dispatch the async action to get the json file like
mounted() {
this.$store.dispatch('getData')
},
And I map the state in my works component like that
export default {
name: 'Works',
computed: mapState({
works: (state) => state.works.home.items.slice(0, state.works.home.loadedCount),
loadedCount: (state) => state.works.home.loadedCount,
totalCount: (state) => state.works.home.items.length,
})
}
I actually need to map the state dynamically based on the route just like state.works[this.$router.currentRoute.params.category] or based on route name.
Could you please tell me what is the correct way to get the data (async) from my state?
Vuex store:
export default new Vuex.Store({
state: {
works: {
all: {
items: [],
loadedCount: 0,
},
home: {
items: [],
loadedCount: 0,
},
web: {
items: [],
loadedCount: 0,
},
print: {
items: [],
loadedCount: 0,
},
},
limit: 2,
},
mutations: {
SET_WORKS(state, works) {
state.works.all.items = works
works.map((el) => {
if (typeof state.works[el.category] !== 'undefined') {
state.works[el.category].items.push(el)
}
})
},
},
actions: {
getData({ commit }) {
axios
.get('/works.json')
.then((response) => {
commit('SET_WORKS', response.data.works)
})
},
},
})
You can do it in beforeCreate hook.
beforeCreate(){
const category = this.$route.params.category;
Object.assign(this.$options.computed, {
...mapState({
categoryItems: (state) => state.categories[category],
}),
});
}
I've created a basic working example: https://codepen.io/bgtor/pen/OJbOxKo?editors=1111
UPDATE:
To get mapped properties updated with route change, you will have to force re-render the component. The best way to do it, is to change the component key when route change in parent component.
Parent.vue
<template>
<categoryComponent :key="key"></categoryComponent> // <-- This is the component you work with
</template>
computed: {
key(){
return this.$route.params.category
}
}
With this approach the beforeCreate hook will be triggered with every route change, getting fresh data from Vuex.

How to reset state values for the component?

I use vuex, and in my page module I set title and content, I arranged a destroyed method to reset them, If I click a different component there is no problem while resetting values but when I click a different static page, component is not destroyed and data is not updated. Is there a way to reset vuex state values for the same component.?
const state = {
page: {},
};
const getters = {
page(state) {
return state.page;
},
};
const mutations = {
setAPage (state, pPage) {
state.page = pPage
state.errors = {}
},
setCleanPage(state){
state.page = null
},
reset(state) {
const s = state();
Object.keys(s).forEach(key => {
state[key] = s[key];
});
console.log('state', state)
}
}
const actions = {
fetchAPage (context, payload) {
context.commit("setCleanPage");
const {slug} = payload;
return ApiService.get(`pages/${slug}/`)
.then((data) => {
context.commit("setAPage", data.data);
})
.catch((response) => {
context.commit("setError", response.data)
})
},
resetAPage(context){
context.commit("reset");
}
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
and in my component :
<script>
import { mapGetters, mapActions, mapMutations } from "vuex";
export default {
name: "Page",
computed: {
...mapGetters('pages', {page: 'page'}),
},
beforeRouteLeave (to, from, next) {
// called when the route that renders this component has changed,
// but this component is reused in the new route.
// For example, for a route with dynamic params /foo/:id, when we
// navigate between /foo/1 and /foo/2, the same Foo component instance
// will be reused, and this hook will be called when that happens.
// has access to >this component instance.
console.log(to)
console.log(from)
console.log(next)
this.$store.dispatch('pages/resetAPage');
},
methods: {
...mapActions(['pages/fetchAPage']),
},
destroyed() {
this.toggleBodyClass('removeClass', 'landing-page');
this.$store.dispatch('pages/resetAPage');
},
created() {
this.$store.dispatch('pages/fetchAPage' , this.$route.params)
},
};
</script>
How can I reset or update data for the same component ?
Thanks
You can use this package for your resets - https://github.com/ianwalter/vue-component-reset
You can use a beforeRouteLeave guard in your component(s) when you want to catch the navigation away from the route where the component is being used (https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards)
The beforeRouteUpdate component guard is called only when the component was used in the current route and is going to be reused in the next route.
I would suggest you watch for that param change.
I don't know how you make use of your params, but you can pass them to your component as props and then add a watcher on them which would call your vuex reset action.
// in your router
// ... some routes
{
path: "/page/:id",
props: true, // this passes :id as prop to your component
component: Page
}
In you component
export default {
name: "Page",
props: ["id"], // your route param
computed: {
...mapGetters('pages', {page: 'page'}),
},
beforeRouteLeave (to, from, next) {
// called when the route that renders this component has changed,
// but this component is reused in the new route.
// For example, for a route with dynamic params /foo/:id, when we
// navigate between /foo/1 and /foo/2, the same Foo component instance
// will be reused, and this hook will be called when that happens.
// has access to >this component instance.
console.log(to)
console.log(from)
console.log(next)
this.$store.dispatch('pages/resetAPage');
},
methods: {
...mapActions(['pages/fetchAPage']),
},
watch: {
id() { // watch the id and reset the page if it has changed or add additionnal logic as needed
this.$store.dispatch('pages/resetAPage');
}
},
destroyed() {
this.toggleBodyClass('removeClass', 'landing-page');
this.$store.dispatch('pages/resetAPage');
},
created() {
this.$store.dispatch('pages/fetchAPage' , this.$route.params)
},
};

(Vue Router) Push params when on a certain route

I have a component, which has programmatic routing based on external data.
The external data is fetched in the App.vue component and used in child components as props.
The data is used in the child component like this:
props: {
externalData: Array
},
computed() {
data() {
return this.externalData
}
}
Here is my router.js (excerpt)
const routes = [
{
path: "/:hae?",
name: "Home",
component: Home
},
{
path: "*",
name: "NotFound",
component: NotFound
}
];
And my Home.vue with the $router.push method (excerpt):
created() {
if (this.$route.path === "/") {
this.$router.push({
params: {
hae: this.data[0].id
}
});
}
},
So here is what i want to achieve:
This is my example array: [{hae: "hae001"}, {hae: "hae002"}, {hae: "hae003"} ...]
When you navigate to https://website.com/ i want the router to redirect you to a param which is the first element of the array, but if you navigate to somewhere else which is not existing in the array (e.g. /something) i want the router to render my NotFound.vue component.
What am i missing?
created() {
const firstDataElementExists = this.data && this.data[0] && this.data[0].hae
if (!firstDataElementExists) {
this.$router.push('/404')
return
}
const isRootPath = this.$route.path === '/'
if (isRootPath) {
this.$router.push(this.data[0].hae)
return
}
const pathIsInData = !!this.data.find(d => d.hae === p)
if (!isRootPath && !pathIsInData) {
this.$router.push('/404')
}
}

Vuejs router listen to events

I have a component wherein the props were passed through the route (https://router.vuejs.org/guide/essentials/passing-props.html). My question is how do I listen to emitted events from the component so that I can mutate the props passed from the route?
In my route I have something like
...
{
path: "details/:id?",
name: "booking.details",
component: BookingDetails,
props: true
}
...
And inside the component I have a props
...
props: {
invoice: {
type: Object,
required: false,
default: () => ({})
}
},
...
methods: {
save () {
this.$emit('reset-invoice') // where do I capture this event
}
}
...
If I understood your question correctly, the listening component would be the <router-view>, so:
<router-view #reset-invoice="resetInvoice"></router-view>
And in whichever component this router view is rendered:
{
methods: {
resetInvoice() {
// ...
}
}
}
You should watch the route and set the props passed from the route, like below
watch: {
'$route' (to, from) {
this.user_id = this.$route.params.id
},
}

Update VueJs component on route change

Is there a way to re-render a component on route change? I'm using Vue Router 2.3.0, and I'm using the same component in multiple routes. It works fine the first time or if I navigate to a route that doesn't use the component and then go to one that does. I'm passing what's different in props like so
{
name: 'MainMap',
path: '/',
props: {
dataFile: 'all_resv.csv',
mapFile: 'contig_us.geo.json',
mapType: 'us'
},
folder: true,
component: Map
},
{
name: 'Arizona',
path: '/arizona',
props: {
dataFile: 'az.csv',
mapFile: 'az.counties.json',
mapType: 'state'
},
folder: true,
component: Map
}
Then I'm using the props to load a new map and new data, but the map stays the same as when it first loaded. I'm not sure what's going on.
The component looks like this:
data() {
return {
loading: true,
load: ''
}
},
props: ['dataFile', 'mapFile', 'mapType'],
watch: {
load: function() {
this.mounted();
}
},
mounted() {
let _this = this;
let svg = d3.select(this.$el);
d3.queue()
.defer(d3.json, `static/data/maps/${this.mapFile}`)
.defer(d3.csv, `static/data/stations/${this.dataFile}`)
.await(function(error, map, stations) {
// Build Map here
});
}
You may want to add a :key attribute to <router-view> like so:
<router-view :key="$route.fullPath"></router-view>
This way, Vue Router will reload the component once the path changes. Without the key, it won’t even notice that something has changed because the same component is being used (in your case, the Map component).
UPDATE --- 3 July, 2019
I found this thing on vue-router documentation, it's called In Component Guards. By the description of it, it really suits your needs (and mine actually). So the codes should be something like this.
export default () {
beforeRouteUpdate (to, from, next) {
// called when the route that renders this component has changed,
// but this component is reused in the new route.
// For example, for a route with dynamic params `/foo/:id`, when we
// navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
// will be reused, and this hook will be called when that happens.
// has access to `this` component instance.
const id = to.params.id
this.AJAXRequest(id)
next()
},
}
As you can see, I just add a next() function. Hope this helps you! Good luck!
Below is my older answer.
Only saved for the purpose of "progress"
My solution to this problem was to watch the $route property.
Which will ended up you getting two values, that is to and from.
watch: {
'$route'(to, from) {
const id = to.params.id
this.AJAXRequest(id)
}
},
The alternate solution to this question handles this situation in more cases.
First, you shouldn't really call mounted() yourself. Abstract the things you are doing in mounted into a method that you can call from mounted. Second, Vue will try to re-use components when it can, so your main issue is likely that mounted is only ever fired once. Instead, you might try using the updated or beforeUpdate lifecycle event.
const Map = {
data() {
return {
loading: true,
load: ''
}
},
props: ['dataFile', 'mapFile', 'mapType'],
methods:{
drawMap(){
console.log("do a bunch a d3 stuff")
}
},
updated(){
console.log('updated')
this.drawMap()
},
mounted() {
console.log('mounted')
this.drawMap()
}
}
Here's a little example, not drawing the d3 stuff, but showing how mounted and updated are fired when you swap routes. Pop open the console, and you will see mounted is only ever fired once.
you can use just this code:
watch: {
$route(to, from) {
// react to route changes...
}
}
Yes, I had the same problem and solved by following way;
ProductDetails.vue
data() {
return {
...
productId: this.$route.params.productId,
...
};
},
methods: {
...mapActions("products", ["fetchProduct"]),
...
},
created() {
this.fetchProduct(this.productId);
...
}
The fetchProduct function comes from Vuex store. When an another product is clicked, the route param is changed by productId but component is not re-rendered because created life cycle hook executes at initialization stage.
When I added just key on router-view on parent component app.vue file
app.vue
<router-view :key="this.$route.path"></router-view>
Now it works well for me. Hopefully this will help Vue developers!
I was having the same issue, but slightly different. I just added a watch on the prop and then re-initiated the fetch method on the prop change.
import { ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import Page from './content/Page.vue';
import Post from './content/Post.vue';
const props = defineProps({ pageSlug: String });
const pageData = ref(false);
const pageBodyClass = ref('');
function getPostContent() {
let postRestEndPoint = '/wp-json/vuepress/v1/post/' + props.pageSlug;
fetch(postRestEndPoint, { method: 'GET', credentials: 'same-origin' })
.then(res => res.json())
.then(res => {
pageData.value = res;
})
.catch(err => console.log(err));
}
getPostContent();
watch(props, (curVal, oldVal) => {
getPostContent();
});
watch(pageData, (newVal, oldVal) => {
if (newVal.hasOwnProperty('data') === true && newVal.data.status === 404) {
pageData.value = false;
window.location.href = "/404";
}
});
router - index.js
{
path: "/:pageSlug",
name: "Page",
component: Page,
props: true,
},
{
path: "/product/:productSlug",
name: "Product",
component: Product,
},
{
path: "/404",
name: "404",
component: Error404,
}