Creating a tree-view in Vue.js that includes clickable components which trigger a Vue.js modal to open up

I have a unique requirement to implement a tree-view feature in Vue-JS for displaying JSON data. However, I need to enhance this by triggering a VueJS modal when any of the data fields in the JSON view are clicked. I have explored various npm modules that offer tree-view functionalities but I am uncertain about how to customize them to enable clickable fields and launch a vue-js modal. Below is my current code snippet for rendering the tree-view, which unfortunately does not support click functionality on the fields.

assets.vue

    <template>

  <div>  

        <h1>The Assets Page</h1>
        <!--<p>{{response}}</p>-->
        <tree-view v-on:click="openGroupModal()" :data="response._embedded.assets" :options="{maxDepth: 0, rootObjectKey: 'Assets'}"></tree-view>
      </div>

</template>
<script>
import axios from 'axios'
import GroupModal from '../assets/assetdetails.vue'
import Vue from 'vue'
import VModal from 'vue-js-modal'
Vue.use(VModal, { dynamic: true })

export default {
  name: 'service',
  data () {
   return {
   response: [],
   errors: []
   }
   },
   
 created () {
      this.callRestService()
    },
 methods: {
   callRestService () {
    axios.get('http://localhost:8080/rest/assets')
   .then(response => {
   // JSON responses are automatically parsed.
   this.response = response.data
   })
   .catch(e => {
    this.errors.push(e)
  })
},
openGroupModal(){

  this.$modal.show(GroupModal,
  {
      draggable: true,
      resizable: true,
      scrollable: true,
      height: "auto",
      width:"50%"
    })
}
 }
}
</script>
<style>
</style> 

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import VueRouter from 'vue-router'
import VModal from 'vue-js-modal'
import App from './App.vue'
import TreeView from 'vue-json-tree-view'

import { routes } from './routes';


Vue.use(VueRouter);
Vue.use(VModal, { dynamic: true })
Vue.use(TreeView)
//Vue.config.productionTip = false

const router = new VueRouter({

  routes  
});


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

Any suggestions?

UPDATE: I implemented Jacob's suggestion but it did not help me with launching the modal. Here is what I tried:

<template>

  <div>  

        <h1>The Assets Page</h1>
        <!--<p>{{response}}</p>-->
        <div @click.capture="openGroupModal($event)">
        <tree-view :data="response._embedded.assets" :options="{maxDepth: 0, rootObjectKey: 'Assets'}"></tree-view>
        </div>
      </div>

</template>
<script>
import axios from 'axios'
import GroupModal from '../assets/assetdetails.vue'
import Vue from 'vue'
import VModal from 'vue-js-modal'
Vue.use(VModal, { dynamic: true })

export default {
  name: 'service',
  data () {
   return {
   response: [],
   errors: []
   }
   },
   
 created () {
      this.callRestService()
    },
 methods: {
   callRestService () {
    axios.get('http://localhost:8080/rest/assets')
   .then(response => {
   // JSON responses are automatically parsed.
   this.response = response.data
   })
   .catch(e => {
    this.errors.push(e)
  })
},
openGroupModal($event){
  console.log("Print message on the console",$event.target);
  this.$modal.show(GroupModal,
  {
      draggable: true,
      resizable: true,
      scrollable: true,
      height: "auto",
      width:"50%"
    })
}
 }
}
</script>
<style>
</style> 

Answer №1

Indeed, a div container might be the solution for you

To achieve this, utilize @click.capture. By adding .capture, an event directed at an inner element will first be handled here before reaching that specific element, as stated in the Vue documentation

You can easily determine which element was clicked on by accessing $event.target

For example:

<template>
  <div @click.capture="openGroupModal($event)">
    <tree-view :data="{1:1,2:{a:'a'}}" :options="{maxDepth: 3}"></tree-view>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  methods:{
    openGroupModal($event){
      console.log($event.target);
      // include other code for displaying modal, etc...
    }
  }
};
</script>

<!-- The "scoped" attribute confines CSS styles to this component only -->
<style scoped>
</style>

This approach has been tested on the HelloWorld.vue component available at https://codesandbox.io/s/nkwk2k095l

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

Executing a pair of queries within the same table and integrating them within a unified route

How can I efficiently execute two queries on the same table in my project? I have been considering using promises, but my knowledge on them is limited. Even though I've researched about it, I am struggling to implement the correct structure. My main ...

Exploring the world of third-party widgets: Comparing Angular, jQuery, and traditional JavaScript

I have a plan to develop a simple embeddable widget similar to Google ads or Facebook like box. Users will be able to easily add the widget to their website and I will extract some parameters to fetch data from my servers. Previously, I relied on jQuery f ...

The provider of $modalInstance is currently unknown, leading to an error in the MainController

I'm currently facing an issue with my app's modals when trying to call them using $modalInstance. Despite following the advice from other similar questions I found, such as avoiding the use of ng-controller, my modal still isn't functioning ...

Error in Uploading Files with AngularJS - Uncaught SyntaxError: Unexpected token

I'm having trouble uploading an image file using Angular and PHP, specifically at the app.service Error line: app.service('fileUpload', ['$https:', function ($https:) { Code app.service('fileUpload', ['$https:&ap ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...

Selecting DigitalOcean city based on user location in Node.js

Currently, I am implementing Node.js in conjunction with my HTTP server. My goal is to have every user who connects to the server be linked to a real-time game server through WebSockets. Furthermore, I aim for users to automatically connect to the nearest ...

Updating image source dynamically with Flask

I am currently developing a face detection application using Flask. I aim to have the detected faces displayed in real-time on the HTML page. For the JavaScript aspect, I am utilizing getUserMedia to live stream camera images from the client to the server ...

Tips for customizing the Electron title bar and enabling drag functionality

Currently, I am embarking on an electron project and my goal is to incorporate a unique custom frame at the top. Does anybody possess knowledge on how this can be achieved? To further clarify, here is a visual representation of what I envision for the cust ...

Add navigation dots to the slider in order to align them with the specified div element

Visit this JSFiddle link for the code <html> <link href="./style.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script&g ...

A Guide to Implementing Inner CSS in Angular

I am working with an object named "Content" that has two properties: Content:{ html:string; css:string } My task is to render a div based on this object. I can easily render the html using the following code: <div [innnerHtml]="Content.html"& ...

Issues with React Material UI Dialog Displaying Incorrect Information

As I experiment with React Material UI dialog boxes, I've encountered an issue that has me puzzled. I have an object 'a', and when I click on a button in a list, it should display the respective ID number. However, instead of showing the cor ...

Converting Persian calendar date to Gregorian in JavaScript

Looking for assistance in converting a date from 1379/10/02 to AD format, specifically to the date 2000/4/29 using the momentJs library. Any help with this task would be greatly appreciated. Thank you! ...

Transforming Google Maps from using jQuery to AngularJS

If I have a Jquery google map with find address and routing system, my goal is to convert it to an angular google map with more options. The current Jquery google map code looks like this: var directionsDisplay = new google.maps.DirectionsRenderer({ d ...

What are some solutions for resolving the issue of a neutralino white screen?

After setting up a new neutralino js application, I encountered an issue where upon running it with the 'neu run' command, all I see is a blank white screen. I tried using the CheckNetIsolation.exe ... command to troubleshoot the problem, but unf ...

How to enable real-time file changes detection in sails for development

I recently embarked on a new project using Sails (built on Express and Node.js). Currently, I am initiating my server with the command: sails lift However, whenever I make changes to the codebase, I need to manually restart the server. Is there a way to ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...

Appending a row to a table will not trigger events in Select2

Despite several attempts, I can't seem to get the select2:select event working on dynamically added rows in a table using select2. The event only works on the original row. Unfortunately, I don't have any additional details about this issue. COD ...

As the user types, automatically format the input field for a seamless and intuitive experience

My current application is running on Angular 1.3.10 I have implemented a jQuery function to automatically add a backslash to the expiration input field once the user types the third number. Although it was a quick fix, I now aim to move this functionality ...

Having trouble with my ReactJS application where click interactions are functioning properly on the header but not on my content

Objective: Implement an iframe displaying a YouTube video with play/pause functionality for users. Issue: Unable to interact with main content, but works correctly when placed in Navigation or Footer components. Attempted Solutions: Explored various de ...