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

I want to hide jqvmap when viewing on mobile devices

I'm currently working on my website at . I have a template that I'm using as a guide, but I want to make the map disappear on mobile view and replace it with a dropdown list. Can anyone suggest what code I should use for this? Appreciate any hel ...

Is there a way to execute .jsx Photoshop scripts on images using Java?

Currently, I am in the process of developing a Java program to apply edits to a sequence of images. However, I am searching for a simple and adaptable method to conduct these edits by utilizing Image Editors Scripts (such as Photoshop Scripts, Gimp Scripts ...

The value is not getting set after calling React Hook UseState

I am currently working on a React component that handles payment processing. There is a part of my code where I utilize the useEffect hook alongside useState to set certain values. Check out the code snippet below: React.useEffect(()=>{ axiosFetch ...

AngularJS expression utilizing unique special character

There are certain special characters (such as '-') in some angular expressions: <tr data-ng-repeat="asset in assets"> <td>{{asset.id}}</td> <td>{{asset.display-name}}</td> <td>{{asset.dns-name}}</td&g ...

Modify the colors of <a> elements with JavaScript

I am brand new to the world of UI design. I am encountering an issue with a static HTML page. (Please note that we are not utilizing any JavaScript frameworks in my project. Please provide assistance using pure JavaScript code) What I would like to achie ...

How do I access a specific child from an object/element retrieved by using the elementFromPoint() method in Javascript?

Is there a method to extract the child element from an element or object retrieved by the function elementFromPoint(x, y); Consider the following scenario: var elem = document.elementFromPoint(x, y); Let's assume that the element returned and saved ...

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...

Installing from a GitHub repository does not always retrieve all of the necessary files

After making some modifications to a specific NPM package by forking the GitHub repository, I am now facing challenges when trying to install it in my project. The command I used to install this modified package is: npm install --save git+https://github.c ...

Guide on integrating npm module in Ionic 1 with AngularJS

Currently working with Ionic 1 and AngularJS, I'm facing an issue where I can't utilize any npm modules due to the error message stating "Error: Cannot find module 'bip39'". ...

Automatically calculate the product of two columns in a gridview

Greetings, I am currently working on a project that involves calculating values from two textboxes within a gridview and displaying the result in a third textbox using JavaScript. The calculation should occur as soon as a value is entered into the second ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Style the div element with CSS

Is there a way to style a div element within an HTML document using Sencha framework? I have specific CSS properties that I would like to apply to my div. #logo{ position:absolute; top:20%; left:0%; } Below is a snippet of my Sencha code: Ex ...

What is the best way to store the dom in cache to ensure that the page remains unchanged when navigating back using the back button?

When adding models to my JavaScript application's model collection using AJAX calls, I encounter an issue where if I click on a model and go to the next page, all the loaded models disappear when I hit the back button. What is the most effective way t ...

Smooth Div Scroll experiencing display issues

Trying to integrate the smooth div scroll, specifically the "Clickable Logo Parade" found at: Successfully implemented it on a blank page exactly as desired, but encountering issues when inserting it into the current layout. Could something be causing int ...

Can you explain how to retrieve the header value from ng-table?

Is there a way to retrieve the table header for each column from JavaScript? When I call tableTest, it only returns data of each row, not the header names like 'name' and 'description'. Is there a method like tableTest.data-title to acc ...

Mongoose is unable to update arrays, so it will simply create a new array

Having trouble updating my collection without any errors. Can someone lend a hand? I've been at this for 3 hours now. const product_id = req.body.cartItems.product_id; const item = cart.cartItems.find(c => c.product_id == product_id); i ...

Error message "TypeError: onClick is not a function" occurs when attempting to use a prop in a functional component

I am encountering issues while trying to utilize the onclick function as props. It shows an error message 'TypeError: onClick is not a function' when I click. What should I do? 7 | <Card 8 | onClick={() => onClick(dish ...

Generate with different HTML elements

This is a simple React code snippet: var Greetings = React.createClass({ render: function() { return <div>Greetings {this.props.name}</div>; } }); ReactDOM.render( <Greetings name="World" />, document.getElementB ...