Display nested files in children of element ui tree using vue - javascript

I am using element ui tree for my vue application. I am implementing 'File browser' type system for my application. In here, files are nested into children.While clicking on child node those nested files or docs will be displaying right side in different container. I am not able to iterate through children and display those files.
**Here is the mocked data :**
data:[{
id: 1,
name: ‘Project A’,
type: ‘folder’,
children: [{
id: 4,
name: 'Project A-1’,
type: ‘folder’,
files: [
{
id: 9,
pid: 4,
name: ‘file 3-A’,
type:’file’,
description: ‘wifi’,
country: ‘USA'
},
{
id: 10,
pid: 4,
name: ‘file 3-B’,
type:’file’,
description: ‘VPN’,
country: ‘USA'
}
]
}
]
},
{
id: 2,
name: 'Services’,
type: 'folder',
children:[],
files: [
{
id: 5,
name: ‘Services-1-A’,
type:’file’,
pid: 2,
description: ‘VPN’,
country: ‘AUS'
},
{
id: 6,
name: ‘Services-1-B’,
type:’file’,
pid: 2,
description: ‘WIFI’,
country: ‘AUS'
}
]
},
{
id: 3,
name: 'Servers',
type: 'folder’,
children:[],
files: [
{
id: 7,
name: ‘Servers-1-A’,
type: ‘file’,
pid: 3,
description: ‘VPN’,
country: ‘CAD'
},
{
id: 8,
name: ‘Servers-1-B',
type: ‘file’,
pid: 3,
description: ‘WIFI’,
country: ‘CAD'
}
]
}]
Here is my UI code
<el-row>
<el-col :span="8" style="background: #f2f2f2">
<div class="folder-content">
<el-tree
node-key="id"
:data="data"
accordion
#node-click="nodeclicked"
ref="tree"
style="background: #f2f2f2"
highlight-current
>
<span class="custom-tree-node" slot-scope="{ node, data }">
<span class="icon-folder">
<i class="el-icon-folder" aria-hidden="true"></i>
<span class="icon-folder_text" #click="showFiles(data.id)">{{ data.name }}</span>
</span>
</span>
</el-tree>
</div>
</el-col>
<el-col :span="16"><div class="entry-content">
<ul>
<li aria-expanded="false" v-for="(file,index) in files" :key="index">
<div class="folder__list"><input type="checkbox" :id= "file" :value="file" v-model="checkedFiles" #click="check">
<i class="el-icon-document" aria-hidden="true"></i>
<span class="folder__name">{{file}}</span></div>
</li>
</ul>
</div></el-col>
</el-row>
Show files method:
showFiles(id) {
let f = this.data.filter(dataObject => {
if (dataObject.children && dataObject.children.id === id) {
return false
} else if (!dataObject.children && dataObject.id === id) {
return false
}
return true
})[0]
this.files = f.files
}
}
I am trying to do like this:

I noticed a bug in your filter function. Check line 3 :
showFiles(id) {
let f = this.data.filter(dataObject => {
//isn't this suppose to return true?
if (dataObject.children && dataObject.children.id === id) {
return false
} else if (!dataObject.children && dataObject.id === id) {
return false
}
return true
})[0]
this.files = f.files
}
Why using filter() method to search for single element? It will scan through all the elements. You could just find() instead to improve performance and better readable code.
Try this:
showFiles(id) {
let f = this.data.find(dataObject => dataObject.id == id);
//ensure node was returned
if(f ){
this.files = f.files
}
}
However, You could try and do this in your component instead.
Add another property to the component's data object. Use the new property to hold the selected node.
data(){
//your mock data
tree:[],
//children files being displayed
files:[]
},
methods:{
showFiles(branch){
this.files = branch.files;
}
}
Then pass the whole object to the method
<span class="icon-folder_text" #click="showFiles(data)">{{ data.name }}</span>

Related

Filter nested v-for list

<div>
<q-card
v-for="box in boxes"
:key="box.id">
<q-item>
<q-item-section>
<span> {{ box.name }} </span>
</q-item-section>
</q-item>
<q-list>
<q-item
v-for="tool in box.tools"
:key="tool.id"
clickable
<q-item-section>
<span> {{ tool.name }} </span>
</q-item-section>
</q-item>
</q-list>
</q-card>
</div>
Form input filter value
inputFilterValue = "box A"
Filter boxes
Edited with return.
computed: {
boxes(){
return boxes.filter(box => {
return box.name.toLowerCase().match(inputFilterValue.toLowerCase())
});
}
}
This works
How to filter too nested v-for box-tools list?
EDITED:
CODEPEN: https://codepen.io/ijose/pen/NWyoRMX
You can use JavaScript filter() along with some() method. some() method checks if any of the elements in an array pass the function.
Demo :
new Vue({
el: '#app',
data: {
value: null,
boxes: [],
dataObj: [{
id: 1,
name: 'Box A',
tools: [{
id: 1,
name: 'Tool A'
}, {
id: 2,
name: 'Tool D2'
}]
}, {
id: 2,
name: 'Box B',
tools: [{
id: 1,
name: 'Tool B'
}]
}, {
id: 3,
name: 'Box C',
tools: [{
id: 1,
name: 'Tool C'
}]
}]
},
mounted() {
this.boxes = structuredClone(this.dataObj);
},
methods: {
inputFilterValue(filterField) {
if (filterField === 'box') {
this.boxes = this.dataObj.filter(box => box.name.toLowerCase().match(this.value.toLowerCase()))
} else {
const filteredToolsArr = this.dataObj.map(box => {
const filteredTool = box.tools.filter((
{ name }) => name.toLowerCase().match(this.value.toLowerCase()));
return { ...box, tools: filteredTool }
})
this.boxes = filteredToolsArr.filter(obj => obj.tools.length);
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
Filter : <input type="text" v-model="value" #keyup="inputFilterValue('tool')"/>
<ul v-for="box in boxes" :key="box.id">
<li>{{ box.name }}</li>
<ul v-for="tool in box.tools" :key="tool.id">
<li>{{ tool.name }}</li>
</ul>
</ul>
</div>
In the filter callback of boxes add a condition if the tool name matches the inputFilterValue
computed: {
boxes(){
return boxes.filter(box => {
return box.name.toLowerCase().match(inputFilterValue.toLowerCase()) ||
box.tools.filter(tool=>tool.name.toLowerCase().match(inputFilterValue.toLowerCase())
});
}
}

I am trying to delete multiple elements from an array through checkbox i am using vue.js but i am unable to figure out how to do it

i have a scenario where I am triggering an event on button click after selecting elements from the grid when the button is clicked I need to remove that element from the current modal/grid
CheckedNames:["a","b","c"],
CheckedNamesId:[1,2,3],
DeletefromArray(){
this.CheckedNames.forEach(element => {
this.deleteItem(this.CheckedNamesId,this.CheckedNamesId.length);
});
},
deleteItem(index,length) {
this.List.splice(index, length)
},
check: function(e,row) {
this.CheckedNamesId.push(row.id)
console.log(this.CheckedNamesId)
},
Now if I select "a","b","c" by the check box, I need to remove it from the array,
If I understood you correctly try something like following snippet:
new Vue({
el: '#demo',
data() {
return {
names: [{id: 1, name: 'a'},{id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'}, {id: 7, name: 'g'}],
checkedNames: []
}
},
methods: {
check(item) {
if (!this.checkedNames.length || !this.checkedNames.find(f => item.id === f.id)) {
this.checkedNames.push(item)
} else {
this.checkedNames = this.checkedNames.filter(f => item.id !== f.id)
}
},
del() {
this.names = this.names.filter(a => !this.checkedNames.includes(a))
this.checkedNames = []
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<ul>
<li v-for="item in names" :key="item.id">
{{ item.name }}
<input type="checkbox" #click="check(item)" />
</li>
</ul>
<button #click="del">Delete</button>
</div>
You can try like the code below. When looping in List array check if id of the element is present in checkedNameID array by using indexof. If present add that element's index in a array defined outside loop. Then you can slice it away using another loop from array. When you slice use 1 as second parameter it will remove 1 element at a a time in loop.
const arr = []
deleteFromArray(){
this.List.forEach((element,index) => {
if(this.checkedNameID.indexOf(element.id) !== -1){
this.arr.push(index);
}
});
arr.forEach(item => {
this.List.splice(index,1);
}
},

How get a load more button for a li list vue js

I'm trying to implement a load more button to my code. I would be able to this in javascript but I can't find a similar way in vue.
This is my vue code. I've tried asking the element with the company id but it's not reactive so I can't just change the style.
<main>
<ul>
<li v-for="company in companiesdb" :key="company.id" v-bind:id="company.id" ref="{{company.id}}" style="display: none">
{{company.name}}<br>
{{company.email}}
</li>
</ul>
</main>
this is my failed atempt of doing it in javascript but as I've mentioned before ref is not reactive so I can't do it this way
limitView: function (){
const step = 3;
do{
this.numberCompaniesVis ++;
let li = this.$refs[this.numberCompaniesVis];
li.style = "display: block";
}while (this.numberCompaniesVis % 3 != step)
}
I think the way you are approaching this problem is a little complex. Instead, you can create a computed variable that will change the number of lists shown.
Here's the code
<template>
<div id="app">
<ul>
<li v-for="(company, index) in companiesLoaded" :key="index">
{{ company }}
</li>
</ul>
<button #click="loadMore">Load</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
companiesdb: [3, 4, 1, 4, 1, 2, 4, 4, 1],
length: 5,
};
},
methods: {
loadMore() {
if (this.length > this.companiesdb.length) return;
this.length = this.length + 3;
},
},
computed: {
companiesLoaded() {
return this.companiesdb.slice(0, this.length);
},
},
};
</script>
So instead of loading the list from companiesdb, create a computed function which will return the new array based on companiesdb variable. Then there's the loadMore function which will be executed every time user clicks the button. This function will increase the initial length, so more lists will be shown.
Here's the live example
Just use computed property to create subset of main array...
const vm = new Vue({
el: '#app',
data() {
return {
companies: [
{ id: 1, name: "Company A" },
{ id: 2, name: "Company B" },
{ id: 3, name: "Company C" },
{ id: 4, name: "Company D" },
{ id: 5, name: "Company E" },
{ id: 6, name: "Company F" },
{ id: 7, name: "Company G" },
{ id: 8, name: "Company H" },
{ id: 9, name: "Company I" },
{ id: 10, name: "Company J" },
],
companiesVisible: 3,
step: 3,
}
},
computed: {
visibleCompanies() {
return this.companies.slice(0, this.companiesVisible)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="company in visibleCompanies" :key="company.id" :id="company.id">
{{company.name}}
</li>
</ul>
<button #click="companiesVisible += step" v-if="companiesVisible < companies.length">Load more...</button>
</div>

Nested Vue components with counts of direct children and nested children

I am trying to implement nested comments in vue.js and nuxt.js.
Each comment can have one or more children comments.
Each child comment, can again, have one or more children comments.
Unlimited levels of nested comments is possible.
As you can see in the diagram I have attached, I would like each comment to "know" (for the sake of simplicity, to display) the following information:
The depth of the comment (I have this working already). Example, all of the "top-level" comments are at depth=0, all their children are at depth=1, and so on.
The number of direct children
the number of children (including nested children, unlimited levels deep)
I came across this question on StackOverflow but it doesn't quite do the trick. Or maybe I am doing something wrong.
In case you want to take a look at my (very messy) code, here it is. However, I'm willing to start over, so appreciate any pointers on how to pass the data up / down the chain of nested comments (vue components). Some sample code would be great.
components/PostComment.vue:
<template>
<div>
<div class="tw-flex tw-flex-wrap tw-justify-end">
<div :class="indent" class="tw-w-full tw-flex">
<div class="tw-font-bold tw-p-4 tw-border-gray-400 tw-border tw-rounded tw-text-right">
<div class="kb-card-section">
<div class="kb-card-section-content tw-flex tw-flex-wrap tw-items-center tw-text-left">
<div class="tw-flex tw-w-full">
<div class="tw-hidden md:tw-block md:tw-w-2/12 tw-text-right tw-my-auto">
<div class="tw-flex">
<p class="tw-w-full tw-text-xs tw-text-gray-600 tw-text-right">children: {{ numNestedChildComments }}, depth: {{depth}}</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="tw-w-full" v-if="commentData.nested_comments" v-for="nestedComment in commentData.nested_comments">
<post-comment
:commentData="nestedComment"
:depth="depth + 1"
:numChildCommentsOfParent=numNestedChildComments
/>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'post-comment', // necessary for recursive components / nested comments to work
props: {
depth: {
type: Number,
required: true
},
postAuthorData: {
type: Object,
required: true
},
commentAuthorData: {
type: Object,
required: true
},
commentData: {
type: Object,
required: true
},
numChildCommentsOfParent: {
type: Number,
required: true
},
},
data() {
return {
numNestedChildComments: this.numChildCommentsOfParent,
}
},
mounted() {
this.incrementNumParentComments();
},
methods: {
incrementNumParentComments() {
this.numNestedChildComments++;
this.$emit('incrementNumParentComments');
},
},
computed: {
indent() {
switch (this.depth) {
case 0:
return "tw-ml-0 tw-mt-1";
case 1:
return "tw-ml-4 tw-mt-1";
case 2:
return "tw-ml-8 tw-mt-1";
case 3:
default:
return "tw-ml-12 tw-mt-1";
}
},
},
}
</script>
Figured it out with some help from Rodrigo Pedra from the Laracasts community.
Here as a parent component calling the tree roots:
<template>
<div>
<MyTree v-for="item in records" :key="item.id" :item="item" />
</div>
</template>
<script>
import MyTree from './MyTree';
const FIXTURE = [
{
id: 1,
children: [
{
id: 2,
children: [{id: 3}, {id: 4}, {id: 5}],
},
{
id: 6,
children: [
{id: 7},
{id: 8, children: [{id: 9}, {id: 10}]},
],
},
],
},
{
id: 11,
children: [
{id: 12, children: [{id: 13}, {id: 14}, {id: 15}]},
{id: 16, children: [{id: 17}]},
{id: 18},
],
},
];
export default {
components: {MyTree},
data() {
return {
records: FIXTURE,
};
},
};
</script>
And here is the tree component:
<template>
<div>
<div style="border: 1px solid black; padding: 5px;" :style="offset">
id: {{ item.id }}
// depth: {{ depth }}
// direct: {{ direct }}
// children: {{ childrenCount }}
</div>
<template v-if="item.children">
<MyTree
v-for="record in item.children"
:key="record.id"
:item="record"
:depth="depth + 1"
#born="handleBorn()" />
</template>
</div>
</template>
<script>
const COLORS = [
'white',
'lightgray',
'lightblue',
'lightcyan',
'lightskyblue',
'lightpink',
];
export default {
// MUST give a name in recursive components
// https://vuejs.org/v2/guide/components-edge-cases.html#Recursive-Components
name: 'MyTree',
props: {
item: {type: Object, required: true},
depth: {type: Number, default: 0},
},
data() {
return {
childrenCount: 0,
};
},
computed: {
direct() {
if (Array.isArray(this.item.children)) {
return this.item.children.length;
}
return 0;
},
offset() {
return {
'margin-left': (this.depth * 20) + 'px',
'background-color': COLORS[this.depth % COLORS.length],
};
},
},
mounted() {
this.$emit('born');
},
methods: {
handleBorn() {
this.childrenCount++;
this.$emit('born');
},
},
};
</script>
Screenshot:

Angular js filter array inside array

I am having a hard time doing an Angular filter to solve a problem as below.
The filter logic is as below:
1) If all listItem of that item has qtyLeft != 0, do not display that item
2) If any of the listItem of that item has qtyLeft == 0, display the item title as well as coressponding listItem that have qtyLeft == 0
Here's a basic example of my data structure, an array of items:
$scope.jsonList = [
{
_id: '0001',
title: 'titleA',
list: {
listName: 'listNameA',
listItem: [
{
name: 'name1',
qtyLeft: 0
},
{
name: 'name2',
qtyLeft: 0
},
]
}
},
{
_id: '0002',
title: 'titleB',
list: {
listName: 'listNameB',
listItem: [
{
name: 'name3',
qtyLeft: 2
},
{
name: 'name4',
qtyLeft: 0
},
]
}
},
{
_id: '0003',
title: 'titleC',
list: {
listName: 'listNameC',
listItem: [
{
name: 'name5',
qtyLeft: 2
},
{
name: 'name6',
qtyLeft: 2
},
]
}
},
]
Here is the final expected outcome:
<div ng-repeat="item in jsonList | filter: filterLogic">
<div> </div>
</div>
// final outcome
<div>
<div>Title: titleA, ListItem: Name1, Name2</div>
<div>Title: titleB, ListItem: Name4</div>
</div>
Created working Plunkr here. https://plnkr.co/edit/SRMgyRIU7nuaybhX3oUC?p=preview
Do not forget to include underscore.js lib in your project if you are going to use this directive.
<div ng-repeat="jsonItem in jsonList | showZeroElement track by $index">
<div>Title:{{ jsonItem.title}}, ListItem:<span ng-repeat="item in
jsonItem.list.listItem track by $index" ng-if="item.qtyLeft==0">
{{item.name}}</span>
</div>
</div>
And
app.filter('showZeroElement', function() {
return function(input) {
var items = []
angular.forEach(input, function(value, index) {
angular.forEach(value.list.listItem, function(val, i) {
var found = _.findWhere(items, {
'title': value.title
})
if (val.qtyLeft === 0 && found === undefined) {
items.push(value)
}
})
})
return items
}
})

Categories

Resources