Showing items in a VueJS component and transferring them to the component

Utilizing VueJS 2.0 and vue-router 2, my goal is to display a template based on route parameters. I have a view called WidgetView where components are dynamically changed. Initially, WidgetComponent is shown which displays a list of widgets. When a user selects a widget or clicks the "New" button in WidgetComponent within WidgetView, I want to switch out WidgetComponent and display the WidgetDetails component, passing information to it:

WidgetComponent.vue:

<template>
...
<router-link :to="{ path: '/widget_view', params: { widgetId: 'new' }  }"><a> New Widget</a></router-link>
<router-link :to="{ path: '/widget_view', params: { widgetId: widget.id } }"><span>{{widget.name}}</span></router-link>
</template>
<script>
  export default {
    name: 'WidgetComponent',
    data() {
      return {
        widgets: [{ id: 1,
        name: 'widgetX',
        type: 'catcher'
      }]}
    }
  }
</script>

WidgetView.vue

<template>
  <component :is="activeComponent"></component>
</template>
<script>
  import WidgetComponent from './components/WidgetComponent'
  import WidgetDetail from './components/WidgetDetail'
  export default {
    name: 'WidgetView',
    components: {
      WidgetComponent,
      WidgetDetail
    },
    mounted: function () {
      const widgetId = this.$route.params.widgetId
      if (widgetId === 'new') {
        // Unable to pass the id to this component 
        this.activeComponent = 'widget-detail'
      }
      else if (widgetId > 0) {
        // Unable to pass the id to this component 
        this.activeComponent = 'widget-detail'
      }
    },
    watch: {
      '$route': function () {
        if (this.$route.params.widgetId === 'new') {
          // How to pass id to this component?
          this.activeComponent = 'widget-detail'
        }
        else if (this.$route.params.widgetId > 0){
          // How to pass id to this component?
          this.activeComponent = 'widget-detail'
        }
        else {
          this.activeComponent = 'widget-component'
        }
      }
    },
    data () {
      return {
        activeComponent: 'widget-component',
        widgetId: 0
      }
    }
  }
</script>

WidgetDetail.vue

<template>
<option v-for="manufacturer in manufacturers" >
    {{ manufacturer.name }}
</option>
</template>
<script>
   export default {
     props: ['sourcesId'],
     ...etc...
   }
</script>

router.js

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/widget_view',
      component: WidgetView,
      subRoutes: {
        path: '/new',
        component: WidgetDetail
      }
    },
    {
      path: '/widget_view/:widgetId',
      component: WidgetView
    },
  ]

})

Although I couldn't get route parameters working, I was able to make the routes work by hard coding them like this:

<router-link :to="{ path: '/widget_view/'+ 'new' }"> New Widget</router-link>

However, I am unsure how to pass an id to the specific template from the script section (not the template) in WidgetView.

Answer №1

If you're interested in learning more about Vue.js routing and passing props, check out this example on jsfiddle: http://jsfiddle.net/ognc78e7/1/. Utilize the router-view element to manage your components effectively. Remember to use props within components to easily pass variables from the URL. For a deeper understanding, refer to the official documentation here: http://router.vuejs.org/en/essentials/passing-props.html

//routes
{ path: '/foo/:id', component: Bar, props:true }
//component
const Bar = { template: '<div>The id is {{id}}</div>',props:['id'] }

Consider different approaches for structuring your routes. You could have the /foo/ path serve as the creation widget and then introduce dynamic /foo/:id paths. Alternatively, follow the example provided where the foo path acts as a starting point leading to various destinations.

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

Is there a way for me to send a form containing pre-existing data from a different page?

Seeking advice: I realize that utilizing jQuery's ajax function may be the simplest approach, however I am facing an issue with the form field names. The var_dump below displays the typical values submitted by the form using test data. It appears that ...

Having trouble with running 'npm init -y' in Windows? Here's a workaround for the VS

An error occurred when trying to initialize npm with the command "npm init -y". The name "WEB DEV" was deemed invalid. For a detailed log of this issue, please refer to: C:\Users\User\AppData\Roaming\npm-cache_logs\2020-12-05 ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

NodeJS presents a potential maze of confusion with its promises

I've been struggling to grasp the concept of asynchronous code execution in NodeJS. My goal is to fetch the output of ip a on a Linux machine and extract the IP Subnet manually. Once that is done, I simply want to use console.log() to display the IP S ...

Is the process.env variable used universally for environmental variables, or is it specifically designed for use in Node.js

Can process.env function as a universal environment variable or is it exclusive to NodeJs? https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_env Instructions on setting it using the node command are provided: $ node -e 'proc ...

Redirecting to a separate component outside the current structure and transferring a callback function

How can I navigate from App.js, the default component, to a new component that is not within the hierarchy while passing a function? I have three components: Question for displaying questions, Upvote for upvoting, and Downvote for downvoting. Here is the ...

Can someone provide guidance on effectively implementing this JavaScript (TypeScript) Tree Recursion function?

I'm currently grappling with coding a recursive function, specifically one that involves "Tree Recursion". I could really use some guidance to steer me in the right direction. To better explain my dilemma, let's consider a basic example showcasi ...

Slideshow feature stops working after one cycle

Hey there! I'm currently working on a function that allows for sliding through a series of images contained within a div. The goal is to cycle back to the beginning when reaching the end, and vice versa when going in the opposite direction. While my c ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Tips for navigating the world of hybrid web applications that combine elements of both traditional multi-page applications and single-page

What are some best practices for developing a multi-page application using modern JavaScript frameworks? Multi-page Application In a multi-page application, we utilize multiple templates with "template syntax" to retrieve backend data and handle AJAX (if ...

What could be causing the closest() method in my JavaScript code to not locate the nearest class?

I've encountered an issue while dynamically creating new classes with input fields in my project. For some reason, when I try to remove a previous row, nothing happens. Can anyone help me troubleshoot this problem? Here is the JavaScript code that I ...

Due to a glitch in the firebase cloud function, the payment is not going through

I have developed a react-redux application with Firestore as the database and now I want to integrate Firebase Cloud Functions to handle Stripe payments. Here is how it's set up: Below is the action method for checkout, which processes token and amo ...

The Node.js server seems to be continuously loading without producing any output

I've been struggling with getting my server to function properly. Whenever I send post data, the page just keeps loading and doesn't display any results. Here is a snippet of my Node.js file: var http = require('http'); var url = requi ...

Set up a Bootstrap date picker to populate two input boxes with a start and end date. Additionally, disable the ability for the date value to change

In my project, I have implemented Bootstrap Datepicker to set two input boxes for selecting start and end dates. The rule is that the start date must be after today and the end date must be after the selected start date. To disable specific dates in the da ...

Access a file from a specified route within Express

Recently, I created a custom Node module that requires a configuration file in CSV format. My goal is to implement this module within an Express Route module; however, I am encountering difficulties related to the loading of the configuration file. Should ...

Listcell XUL with button options

How can I make buttons inside a listcell function in XUL? I am having trouble getting it to work. Here is the XUL code: <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label ...

When the ng-model is updated within a promise's .then() function, the ng-change

I've encountered an issue with ng-change in a select not triggering when I update the ng-model parameter within my promise.then function. Here's my select code: <select ng-model="currentReport" ng-options="rpt.ReportDisp for rpt in availa ...

ThreeJs is known for effortlessly handling an abundance of vertices, far surpassing the number typically found

I came across this code snippet: function loadObject(filePath){ var loader = new THREE.OBJLoader(); loader.load( filePath, function ( object ) { child = object.children[0]; var geometry = new THREE.Geometry().fromBufferGeometry( ch ...

Is there a way for me to programmatically modify a .env file using an npm script?

Currently, I'm managing a project with a .env file that contains confidential information. One of the key elements in this file is 'STATUS'. Just to clarify, this pertains to a Discord bot, The value assigned to the 'STATUS' var ...

Developing a RESTful API using NodeJS that interacts with Python to handle JSON data and trigger

I've recently started working on a new project and I'm in need of some assistance from experienced individuals. The foundation of my project is based on this tutorial: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4, whi ...