Implementing mixin functions in vue.router routes with Vue.js

Is there a way to dynamically change the title of the window based on each route? I have included a meta: { title: ... } object in each child object within the routes: []. Here is an example:

routes: [
{
  path: 'profile/:id',
  name: 'Profile',
  component: Profile,
  meta: {
    title: function (to, cb) {
      const profileId = parseInt(to.params.id);
      // ... do stuff ...
    }
  }
}
]

I am trying to call this title function using an afterEach hook:

router.afterEach((to) => {
    document.title = 'My Site';
    if (to.meta && to.meta.title) {
        to.meta.title(router.app, to, (result) => { document.title += ' | ' + result; });
    }
});

Within the ... do stuff ... section, I need to use a method from my mixin GetAndStore.js called loadProfile(profileId). Even after adding GetAndStore to the router's mixins and loading it globally, I am unable to access loadProfile as it shows as undefined (this.loadProfile). Despite trying various configurations for over an hour, I have been unsuccessful in accessing methods from the GetAndStore mixin within this setup.

Any suggestions on what might be missing or how I can restructure to access mixin methods within

routes->element->meta->title
?

Answer №1

The main concern here is...

Mixins offer a versatile method to share reusable functionalities for Vue components

It's important to note that Vue-router is not considered a component, and the component loaded for the route may not be directly accessible.

One suggestion would be to transform loadProfile into a named export from your GetAndStore mixin. Assuming your mixin is exported as shown below:

import axios from 'axios' // just an example

export default {
  methods: {
    loadProfile (profileId) {
      return axios.get(...)
    }
  }
}

You can separate the function from the default export and assign it a name like this:

export function loadProfile (profileId) {
  return axios.get(...)
}

export default {
  methods: {
    loadProfile
  }
}

Then, in your route definitions, you can import only the loadProfile function:

import { loadProfile } from 'GetAndStore'

Alternatively, you could import your mixin as is and utilize it by calling:

import GetAndStore from 'GetAndStore'

// snip

GetAndStore.methods.loadProfile(to.params.id).then(...)

Answer №2

One approach could be implementing the logic within the beforeRouteEnter method inside the Profile component. This way, you can extract the meta title and dynamically set the page title. Additionally, this method provides access to mixin methods for further functionality:

beforeRouteEnter (to, from, next) {
  if (to.meta && to.meta.title) {
    to.meta.title(router.app, to, (result) => { document.title += ' | ' + result; });
  }
},

For more information, refer to the documentation: https://router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for retrieving the content of an input field using Angular

function HomeController($scope, navbarService) { var vm = this; $scope.showHeader = true; $scope.userNameNav =''; $scope.$on('toggleHeader', function(event, data) { $scope.showHeader = data; }); $s ...

I encountered the "Unknown keystone list" error when I first began using the app on Keystone 4.0

I have implemented routes to post event data. var keystone = require('keystone'); var Event = keystone.list('Event'); module.exports = function (req, res) { if (!req.body.name || !req.body.startTime || !req.body.endTime) { retu ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...

Tips for quickly rendering over 10,000 items with React and Flux

What is the most efficient way to render a large number of items in React? Imagine creating a checkbox list with over 10,000 dynamically generated checkbox items. I have a store that holds all the items and serves as the state for the checkbox list. Whe ...

Tips for utilizing the 'contains' feature within web elements with Java Selenium WebDriver?

In my current project, I am facing a challenge with two specific elements: one is a string formatted as ABC £12,56 and the other is a box called "Cashbox" that should be 15% of the value of the string. However, when attempting to locate the CSS for both e ...

Describe the ng-model for this specific JSON input array in AngularJS

Aim: The task at hand is to update the data in the following format: "open_hours": [ // (Note that open_hours is an array). { "weekday": "mon", "opens_at": "09:00", "closes_at": "22:00" }, { "weekday": "t ...

Conceal a div once the user scrolls to a certain position using vanilla JavaScript

As a beginner in the field of web development, I am currently working on creating a blog website. Code Function - One of the challenges I'm facing is implementing a floating pagination bar that needs to be hidden when a visitor scrolls near the foote ...

Style the code presented within a div tag

I am in the process of creating a JavaScript-powered user interface that can generate code based on user interactions. While I have successfully implemented the code generation functionality and saved the generated code as a string, I am facing difficultie ...

Struggling with combining model and textures in three.js

Here in this fiddle, you can find an example of the issue I am facing: http://jsfiddle.net/saward/78Bjk/7/ If you uncomment scene.add(tree_mesh) and scene.add(mesh2), and comment out scene.add(mesh), you will be able to see both objects. However, when I m ...

invoking a function at a designated interval

I am currently working on a mobile application built with Ionic and TypeScript. My goal is to continuously update the user's location every 10 minutes. My approach involves calling a function at regular intervals, like this: function updateUserLocat ...

What are the steps to making a textfield editable with JavaScript and HTML?

My textfield is currently populated with values from the database and is functioning perfectly. I would like to implement a checkbox feature that, when clicked, will clear the textfield of the database values, allowing the user to input new values. If t ...

Positioning a div on the right side of its parent div

Hi there! I'm currently working on a small navbar that has two sections: the left section with an arrow icon and the right section with two icons - an envelope and an exclamation triangle. I've been trying to position the right section in the top ...

The JavaScript code runs first before retrieving any information from the server

When it comes to validating coupons on Stripe, the process needs to be done on the server side rather than the client side. I've tackled this by writing some code for validation, but I'm facing challenges with synchronizing the AJAX/JSON response ...

Tips for implementing a nested ng-repeat with nested JSON array data triggered by a button click

Assuming I have assigned the following JSON data to $scope.people: [ { "personId": 1, "name": "Thomas", "age": 39, "friends": [ { "friendId": 1, "nickName": "Lefty" ...

I have added the same directive to both of my HTML files

Hello, I am facing an issue with a directive that I have included in two HTML files. The 'app' is set as ng-app. <dir auto=""></div> The code for the directive is as follows: app.directive("auto", function() { scope: { arr : ...

Preventing flickering when updating UI elements with AngularJS

A website I created showcases a variety of progress bars, each representing the progress of various backend tasks. For example: <div ng-repeat="job in jobs"> <div id="progressbar">...</div> </div> I am using a $resource for the ...

Steps for dynamically loading the content of a Bootstrap 4 Modal

I am currently in the process of developing a website that will showcase a wide range of images. The design is set up as a landing page with all content contained within the main HTML page - there is only an index.html file for now. This website will serv ...

What steps can be taken to address the issue of the body-parser module being disabled in a node

My API is not functioning properly and I have observed that the body-parser module seems to be disabled in some way. Despite my efforts, I have been unable to find any information on this issue. Please refer to the image attached below for further details. ...

What steps should I take to delete a class from my calendar after it has reached the maximum capacity of 20

I am trying to create a feature that automatically removes a class from the calendar if more than 20 people have booked it. On the admin side of the system, I can add classes to the database but need help implementing this check. Below is my current code ...

The removeAttribute function has the ability to remove the "disabled" attribute, but it does not have the capability to remove

When it comes to my JavaScript code, I have encountered an issue with two specific lines: document.getElementsByName('group')[0].removeAttribute('disabled'); document.getElementsByName('group')[0].removeAttribute('checke ...