Tips for accessing array values dynamically in Vuejs from an existing array?

WelcomeWorld.vue

export const dataList = [
  { id: 1, val: "11", kk: "potter" },
  { id: 2, val: "22", kk: "james" },
  { id: 3, val: "55", kk: "limda" },
  { id: 4, val: "77", kk: "stepen" }
];
 
<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.id">
      <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        {{ item.kk }}
      </router-link>
    </div>
    <br /><br /><br />
    <User />
  </div>
</template>

<script>
import User from "./User.vue";
import { dataList } from "./dataList";
export default { 
  name: "WelcomeWorld",
  components: {
    User,
  },
  data() {
    return {
      items: dataList,
    };
  },
};
</script>

User.vue

import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import WelcomeWorld from "./components/WelcomeWorld.vue";
import book from "./components/book.vue";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    { path: "/", name: "User", component: WelcomeWorld },
    { path: "/", name: "BookWithID", component: book },
    { path: "/:id", name: "UserWithID", component: WelcomeWorld }
  ]
});

Vue.config.productionTip = false;

new Vue({
  router,
  render: (h) => h(App)
}).$mount("#app");
export const dataListTwo = [
  { id: 1, book: "steel", pen: "p1", gap: "1" },
  { id: 2, book: "iron", pen: "jp2", gap: "5" },
  { id: 3, book: "platinium", pen: "p3", gap: "2" },
  { id: 4, book: "gold", pen: "p4", gap: "9" }
];
<template>
  <div>
    <router-link :to="{ name: 'BookWithID' }">
      {{ user.book }}
    </router-link>
  </div>
</template>

<script>
import { dataListTwo } from "./dataListTwo";
export default {
  name: "User",
  components: {},
  data() {
    return {
      lists: dataListTwo,
    };
  },
  computed: {
    user: function () {
      return this.lists.find((item) => item.id === this.$route.params.id);
    },
  },
};
</script>

In the dataListTwo.js, I have array values such as steel and pen. I want to call both of them together like steel/pen as an API call in the mounted().

When I click on the router-link, {{ user.book }} from the User.vue component.

For example, I want to pass the pen/gap array values as query parameters when clicked on {{ user.book }} from the User.vue component. Please go through CodeSandbox once. I tried adding a computed property for pen and gap, but pen/gap are not calling dynamically.

Here is my code: https://codesandbox.io/s/new-hill-6yum4o?file=/src/components/User.vue

Answer №1

Your question and description are a bit unclear, so I'll do my best to provide an answer based on my understanding. If this is not what you were looking for, please clarify your query.

Firstly, make sure to clearly define your routes. It seems like you have two routes both pointing to '/'. Consider organizing them so that your user index is at '/', your book is at '/book/:id', and your user is at 'user/:id'.

Secondly, it appears that HelloWorld.vue is included in both User and UserWithId routes. If this is intentional, then no changes are needed. However, if it's not intended, you should clean up the file to ensure each route points to the correct component.

Thirdly, based on your example involving Potter, assuming you are referring to the book component (code for which is missing), you can access the data as follows:

...
computed: {
  book() {
    if (this.$route.params.id == null || this.$route.params.id == undefined) {
      throw new Error('No book id provided')
    }
    return datalisttwo.find(_ => _.id == this.$route.params.id)
  },
  pen() {
    this.book.pen
  },
  gap() {
    this.book.gap
  }
}
...

Using this approach, you can manipulate this.pen and this.gap as needed.

If you wish to avoid importing data list again, you can pass your retrieved pen & gap as query parameters. Refer to https://router.vuejs.org/api/ for more information.

Answer №2

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";
import book from "./components/book.vue";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    { path: "/", name: "User", component: HelloWorld },
    { path: "/", name: "BookWithID", component: book },
    { path: "/:id", name: "UserWithID", component: HelloWorld }
  ]
});

Vue.config.productionTip = false;

new Vue({
  router,
  render: (h) => h(App)
}).$mount("#app");
export const datalisttwo = [
  { id: 1, book: "steel", pen: "p1", gap: "1" },
  { id: 2, book: "iron", pen: "jp2", gap: "5" },
  { id: 3, book: "platinium", pen: "p3", gap: "2" },
  { id: 4, book: "gold", pen: "p4", gap: "9" }
];
<template>
  <div>
    <router-link :to="{ name: 'BookWithID' }">
      {{ user.book }}
    </router-link>
  </div>
</template>

<script>
import { datalisttwo } from "./datalisttwo";
export default {
  name: "User",
  components: {},
  data() {
    return {
      lists: datalisttwo,
    };
  },
  computed: {
    user: function () {
      return this.lists.find((item) => item.id === this.$route.params.id);
    },
  },
};
</script>

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

Issue with iview-ui: Unable to make admin panel full height. The iView example suggests using min-height: 200px

Is there a reason why the iView admin template can only scale to a preset height? Can someone assist me in setting the height of the admin to fill the entire browser (100vh or 100%)? Many thanks in advance. The example on the site displays a predefined m ...

Storing information in an array with automatic ID generation_incrementing

Here is an array in a specific format, however, there is no "ID" field available when the form is submitted. The requirement is to have an auto-generated ID assigned and saved in a JSON Array upon user submission of the form. With each form submission, t ...

Troubleshooting Issue with PUT Request in React Front-End Application with Axios Implementation

Currently, I am working on a MERN exercise tracker project that I found online. The backend is functioning perfectly with all CRUD operations working smoothly. However, I have run into an issue with the React frontend when trying to edit or update data. Th ...

Notify the parent component about the connectivity status of the children

I'm currently developing an application using React and Electron. One of the components I'm working on involves opening three TCP sockets and rendering children once all connections are established. Here's a simplified version of what it loo ...

Controlling dropdown menus filled with AJAX responseData

When it comes to Javascript, JQuery has always been a reliable companion for me. However, there are instances where I encounter challenges that require some extra effort to overcome. Today happens to be one of those days. I've stumbled upon an issue t ...

What is the best way to change the content in a textarea field?

I am looking to create a functionality where a div is displayed below selected text inside a textarea. Below is the JavaScript code: function getSel() { var txtarea = document.getElementById("mytextarea"); var start = txtarea.selectionStart; ...

Retrieve the text inside the DIV that contains the clicked link

I'm facing an issue with my JS code: $(document).on("click", '.like', function (e) { $(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>"); ...

Navigate to a different URL following a post request using AJAX and EXPRESS

Currently, I am diving into the world of node.js servers by creating a login website. Users can input their username, which is then sent via an ajax post request to the server and stored in an array of all users. My goal is to redirect users to a personali ...

Fetch search results dynamically in Wordpress through AJAX

I'm struggling to implement AJAX on my WordPress site to display search results without refreshing the page. Despite trying various solutions found through research, none seem to be working effectively for me. Currently, here is the progress I have ma ...

Show informational pop-up when hovering over selected option

My goal is to create an information box that appears when a user hovers over a select option. For example: <select id = "sel"> <option value="sick leave">Sick leave</option> <option value="urgent leave">Urgent lea ...

Tips for enabling Angular JS draggable elements on tablet devices with touch functionality

I've been experimenting with an Angular JS draggable directive. The code I'm using closely resembles the one in this Plunker example. While everything runs smoothly on Windows when using a mouse, I've encountered issues with touch-enabled d ...

How to send arguments to an external JavaScript file with JavaScript

In the header of my HTML document, I have included the following script: <script src="http://www.domain.com/js/widgets.js" type="text/javascript"></script> This script references: widgets.js (function () { var styleEl = document.create ...

A method for retrieving a collection of information from a Mongoose model

I am working on a function within Express to retrieve a list of data from a mongoose model. The 'MiModelo' model is created using a Schema. //Retrieving data from the database function getAllData() { var promise = MiModelo.find().exec(); ...

Converting Coordinated Universal Time (UTC) to local Unix time: A step

I am currently working on a React application that includes a survey component. When a user decides to skip the survey, I want it to reappear after a certain amount of time has passed (measured in days or hours). The rejected time is provided in UTC format ...

Encountering an error message related to Bootstrap carousel: "Unable to read property 'offsetWidth' of undefined"

Encountering a frustrating error message: "Cannot read property 'offsetWidth' of undefined" when using Bootstrap carousel. Let me share my code with you: <div id="myCarousel" class="carousel slide" > <ul class=& ...

Is there a way for me to receive user inputs, perform mathematical operations on them, and then display the result of the calculation? Additionally, is there a way to ensure that the output value automatically updates

As a newcomer to HTML and JavaScript, I'm unsure how to approach this task. Here is what I have so far: <div class="inputs"> <label for="#arena2v2">2v2 Arena Rating:&#9;</label><input class="pvp" type="number" step="1" m ...

Material Design - The element provided is not valid: it should be a string for built-in components or a class/function for composite components, but instead it is an object

How are you today? I am currently working on a React project using Webpack and Babel. I encountered an issue when trying to incorporate Material UI components from https://mui.com/. Whenever I import a MUI component into my project, I receive the followin ...

Unit testing Vue 3 by simulating the push() method of vue-router

As a newcomer to Vue and StackOverflow, I wanted to share my issue. While attempting to run the unit test for my application, I encountered a TypeError. The error message stated: "TypeError: Cannot read properties of undefined (reading 'push')" ...

Changing the texture on a material in three.js

I have successfully set up a texture on a mesh using three.js, and it initially loads exactly as I want it to: texture = THREE.ImageUtils.loadTexture("textures/hash.png"); texture.needsUpdate = true; uniforms = { colo ...

Modifying webpage code

I am looking to develop a system where I can edit various elements such as the navbar, paragraphs, and images directly from a web page. I understand that this can be achieved with JavaScript, but I am facing the issue of my customizations reverting to defa ...