Vue JS - Rendering Multidemensional Obj - vue-component

I'm new to VUE, and having a hard time figuring out how to render an Object where i don't know how many levels deep it will go.
i get this object returned from a web-api
var result = {
"1":{
"id":"1",
"parent_id":"-1",
"name":"Master",
"level":1,
"children":{
"2":{
"id":"2",
"parent_id":"1",
"name":"Category A",
"level":2,
"children":{
"5":{
"id":"5",
"parent_id":"2",
"name":"Category D",
"level":3
},
"6":{
"id":"6",
"parent_id":"2",
"name":"Category E",
"level":3,
"children":{
"10":{
"id":"10",
"parent_id":"6",
"name":"Category F",
"level":4
}
}
}
}
},
"3":{
"id":"3",
"parent_id":"1",
"name":"Category B",
"level":2,
"children":{
"4":{
"id":"4",
"parent_id":"3",
"name":"Category C",
"level":3
}
}
}
}
}
};
I ignore the first level and push it in my store. Now i'm looking for a recursive way to go over all the parent's and theire children.
(this would be an example of the desired output)
<ul>
<li>Master</li>
<ul>
<li>Category A</li>
<ul>
<li>Category D</li>
<li>Category E</li>
<ul>
<li>Category F</li>
</ul>
</ul>
<li>Category B</li>
<ul>
<li>Category C</li>
</ul>
</ul>
</ul>
However i do not get further then:
<ul>
<li>Master</li>
<ul>
<li>Category A</li>
<li>Category B</li>
</ul>
</ul>
And offcourse i could go on like this and then i'll reach the end of my obj. but in real situation i don't know how deep it will go, that's why i want a solution that doesn't care about that and continiu's till there are no more children.
I saw a little something in the doc's but that code is so different from mine that i cant really understand how to apply ( https://v2.vuejs.org/v2/guide/components.html#Circular-References-Between-Components )
My init code is basically this is everything (simplified) together :
store = function() {
var self = this;
self.hierarchies = [];
self.subView = 'hierarchies';
self.tree = [];
};
Vue.component('hierarchies', {
template: '#hierarchies',
props: ['store']
});
Vue.component('products', {
template: '#products',
props: ['store']
});
Vue.component('treeview', {
template: '#treeview',
props: ['store']
});
app = new Vue({
el: '#content',
data: function () {
return {
store: {},
tree: {}
}
},
created: function () {
this.store = new store();
}
});
// DO AXJAX REQUEST GET HIERARCHY'S
var response = // AJAX {};
app.store.tree.push(response[1]);
<template id="treeview">
<div>
<ul v-if="store.tree.length">
<li v-for="m in store.tree">
{{ m.name }}
<ul v-if="m.children">
<li v-for="c in m.children">
{{ c.name }}
</li>
</ul>
<data :tree="m"></data>
</li>
</ul>
</div>
</template>
All idea's suggestions are welcome :)
Best,
Bastian

Your data is in a pretty unpractical format since you cannot loop over object keys using the v-for directive. So in order to consume that format, you have to transform it into an array first. I’m using a computed property for that, but a better solution for the long run might be to transform the data once in the beginning or even changing the result format of your web service (if you can).
var result = {"1":{"id":"1","parent_id":"-1","name":"Master","level":1,"children":{"2":{"id":"2","parent_id":"1","name":"Category A","level":2,"children":{"5":{"id":"5","parent_id":"2","name":"Category D","level":3},"6":{"id":"6","parent_id":"2","name":"Category E","level":3,"children":{"10":{"id":"10","parent_id":"6","name":"Category F","level":4}}}}},"3":{"id":"3","parent_id":"1","name":"Category B","level":2,"children":{"4":{"id":"4","parent_id":"3","name":"Category C","level":3}}}}}};
Vue.component('tree-root', {
props: ['items'],
template: `
<ul>
<tree-item v-for="item in items" v-bind:item="item"></tree-item>
</ul>
`
});
Vue.component('tree-item', {
props: ['item'],
computed: {
children: function () {
return Object.keys(this.item.children).map(k => this.item.children[k]);
}
},
template: `
<li>
{{item.name}}
<tree-root v-if="item.children" v-bind:items="children"></tree-root>
</li>
`
});
var app = new Vue({
el: '#app',
data: {
rootItem: result['1']
}
});
<ul id="app">
<tree-item v-bind:item="rootItem"></tree-item>
</ul>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
What I’m doing here is use two components: tree-root which is responsible for rendering a list of items, and tree-item which is responsible for rendering a single item, eventually recursively rendering another tree-root for the children of each item.
The computed children property is used to transform the children object into a list of children.
Finally, in order to render the root component, we just render the result['1'] which is the root element as a tree-item. We could also render a tree-root instead with the whole result but then we would have to convert it first into an array (just like in the computed property), so I just opted with the simpler solution here.

Related

Vue3 Dropdown Click ul show

I want to do something like this in my project below, but every time I click it, it seems as if each element is selected.
What I want to do is simply,
When handleShow(depth) is clicked;
I want to print the clicked depth value in selected and show its ul, but it does not satisfy the condition I wrote.
v-show="selected === depth"
<template>
<li v-if="items.children" class="item dropdown">
<router-link
:link="items"
:key="depth"
#click.stop="handleShow(depth)"
/>
<ul class="dropdown-menu" v-show="selected === depth">
<MenuItems
v-for="(child, childIndex) in items.children"
:key="childIndex"
:items="child"
/>
</ul>
</li>
<li v-else class="item">
<router-link
:link="items"
:key="depth"
/>
</li>
</template>
<script>
import {ref, defineComponent} from "vue"
export default defineComponent({
name: 'MenuItems',
components: {MenuLink},
props: {
items: {type: Object, required: true},
depth: Number,
},
setup() {
let selected = ref(null);
const handleShow = (depth) => {
selected.value = depth;
}
return {
handleShow,
selected
}
},
})
</script>

Vue v-if not reading variable

I am using Vue 2 on Laravel 5.3 (using bxslider for carousel)
The following code gives me a single image (img1) slider.
If I remove v-ifs it does give me 3 image (with img1 img2 img3 in the slider).
Does productChoiceSelected.img2 returns true if it is not null from the database?
EDIT (added full code of the component)
<div class="col-md-4">
<ul class="bxslider">
<li>
<img :src="productChoiceSelected.img1">
</li>
<li v-if="productChoiceSelected.img2">
<img :src="productChoiceSelected.img2">
</li>
<li v-if="productChoiceSelected.img3">
<img :src="productChoiceSelected.img3">
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data(){
return{
product:[],
productChoiceSelected:[],
productChoices:[]
}
},
props:[
'productId'
],
mounted(){
this.getProduct()
this.getAllProductChoices()
},
methods:{
getProduct(){
var vm = this;
vm.$http.get('/getProduct/'+vm.productId).then((response)=>{
vm.product = response.data.data.product;
vm.productChoiceSelected = response.data.data.productChoiceDefault;
});
},
getAllProductChoices(){
var vm = this;
vm.$http.get('/getAllProductChoices/'+vm.productId).then((response)=>{
vm.productChoices = response.data.data.productChoices;
});
}
}
}
</script>
EDIT #2
I guess it is because productChoiceSelected.img2 is a url directory? it is http://localhost:8000/img/products/1-2.bmp
I can figure out few issues in your code:
You need to have img1 and these variables defined as these are to be set reactively to be used in vue templated.
You need to move $('.bxslider').bxSlider({}) code in the updated section as this needs to be executed once you get the data updated from backend.
Following are code changes:
var demo = new Vue({
el: '#demo',
data: function(){
return {
productChoiceSelected: {
img1:'',
img2:'',
img3:''
}
};
},
mounted(){
this.getProduct()
},
updated(){
$('.bxslider').bxSlider({});
},
methods:{
getProduct(){
var vm = this;
setTimeout(function () {
vm.productChoiceSelected.img1 = 'http://bxslider.com/images/730_200/hill_trees.jpg'
// vm.productChoiceSelected.img2 = 'http://bxslider.com/images/730_200/houses.jpg'
vm.productChoiceSelected.img3 = 'http://bxslider.com/images/730_200/hill_fence.jpg'
}, 300)
}
}
})
see updated fiddle.
Thanks for saurabh contribution above, as I am still unsure where the problem is, here is how I solve the problem by myself for you guys' reference.
Change in code:
<template>
<div class="col-md-5">
<div class="col-md-12">
<ul class="bxslider">
<li>
<img :src="productChoiceSelected.img1">
</li>
<li v-if="img2">
<img :src="productChoiceSelected.img2">
</li>
<li v-if="img3">
<img :src="productChoiceSelected.img3">
</li>
</ul>
</div>
</div>
.....
.....
.....
methods:{
getProduct(){
var vm = this;
vm.$http.get('/getProduct/'+vm.productId).then((response)=>{
vm.product = response.data.data.product;
vm.productChoiceSelected = response.data.data.productChoiceDefault;
if(vm.productChoiceSelected.img1){
vm.img1 = true
}
if(vm.productChoiceSelected.img2 != null){
vm.img2 = true
}
if(vm.productChoiceSelected.img3 != null){
vm.img3 = true
}
});
},
......
......
......

set CSS class depending on returned string with Ember

Im still learning ember and i didn't got how i can apply certain CSS class depending on the returned string of a model on a certain controller.
The official documentation (http://emberjs.jsbin.com/yoqifiguva/1/edit?html,js,output) only covers when you have a boolean.
I didn't manage to apply this knowledge for my case.
I have status string string like : "passed", "failed", "pendent" and "blocked", which i want to apply different css class for each status.
Any examples on how to achieve that?
You can use bind-attr, for example:
<ul>
{{#each item in model}}
<li {{bind-attr class='item.status'}}>An item with status: `{{item.status}}`</li>
{{/each}}
</ul>
Which produces following HTML:
<ul>
<li class="passed" data-bindattr-262="262">An item with status: `passed`</li>
<li class="failed" data-bindattr-265="265">An item with status: `failed`</li>
</ul>
For collection:
[
YourModel.create({ status: 'passed'}),
YourModel.create({ status: 'failed'})
]
of objects declared like:
YourModel = Em.Object.extend({
status: null
});
Demo.
You can also create Component which can be reused with many models.
Component code:
App.StatusItemComponent = Em.Component.extend({
classNameBindings: ['status'],
status: function() {
var modelStatus = this.get('model.status');
if (modelStatus)
return 'status-' + modelStatus;
}.property('model.status')
});
Template code:
{{#each item in model}}
{{#status-item model=item}}
An item with status: {{item.status}}
{{/status-item}}
{{/each}}
Demo.

Translate Handlebars block helpers using end tags into Meteor?

In Meteor, I have an app where I make a list of items grouped by tags, where non-tagged items come first and then tagged items are hidden under a "tag header" drop down.
I haven't touched this app since 0.8 came out, and I was using a block helper in a template which worked fine in pre-0.8...
See working jsfiddle here
Handlebars.registerHelper('eachItem', function(context, options) {
var ret = "";
for(var i=0, j=context.length; i<j; i++) {
if(!context[i].tag){
ret = ret + options.fn(context[i]);
} else {
if(i===0||!context[i-1].tag ||context[i-1].tag !== context[i].tag){
ret = ret + '<li class="list-group-item"><a data-toggle="collapse" data-target="#'+ context[i].tag +'"> Items tagged '+context[i].tag + '</a></li><div id="'+context[i].tag+'" class="collapse">';
}
ret = ret + options.fn(context[i]);
if(i+1<j && context[i+1].tag !== context[i].tag){
ret = ret + '</div>';
}
}
}
return ret;
});
But I'm struggling a bit to translate this into post-0.8 Meteor
The inserted HTML must consist of balanced HTML tags. You can't, for example,
insert " </div><div>" to close an existing div and open a new one.
One idea I had was to render the non-tagged items and also the containers in a vanilla {{#each}} loop (with 2 different templates), and then do something like this
Template.myListContainer.rendered = function(){
_.each(tags, function(tag){
var tagged_items = _.filter(items, function(item){ return item.tag == tag; });
_.each(tagged_items, function(item){
UI.insert(UI.RenderWithData(listItemTemplate, { item : item }), tagContainer);
});
});
}
Is there a simpler way to do this ? If the items come from a collection, will they keep their reactivity ?
Many thanks in advance !
If you haven't already, it's worth reading the Meteor wiki on migrating to blaze.
Anyhow, this one seems difficult to implement as a straight iteration.
If you don't need them in a specific order, I would just list items w/ and w/o tags, eg:
Template.example.helpers({
dataWithoutTags: function(){
return items.find({tag:{exists: false}});
},
tagList: function(){
// create a distinct list of tags
return _.uniq(items.find({tag:{exists: true}}, {tag: true}));
},
dataForTag: function(){
// use `valueOf` as `this` is a boxed-string
return items.find({tag: this.valueOf()});
}
});
Template:
<template name="example">
<div class='panel panel-default'>
<ul class='list-group'>
{{#each dataWithoutTags}}
<li class='list-group-item'>{{name}}</li>
{{/each}}
{{#each tagList}}
<li class="list-group-item">
<a data-toggle="collapse" data-target="#{{this}}"> Items tagged {{this}}</a>
</li>
<div id="{{this}}" class="collapse">
{{#each dataForTag}}
<li class='list-group-item'>{{name}}</li>
{{/each}}
</div>
{{/each}}
</ul>
</div>
</template>
If you do need them in a specific order - eg. grouping only consecutive items (as per your example). The only option would be to pre-process them.
eg:
Template.example.helpers({
itemsGrouped: function(){
dataGroups = [];
currentGroup = null;
items.find({}, {sort: {rank: 1}}).forEach(function(item){
if (currentGroup && (!item.tag || currentGroup.tag != item.tag)){
dataGroups.push(currentGroup);
currentGroup = null;
}
if (item.tag){
if (!currentGroup){
currentGroup = {
group: true,
tag: item.tag,
items: [item]
};
} else {
currentGroup.items.push(item);
}
} else {
dataGroups.push(item);
}
});
if (currentGroup){ dataGroups.push(currentGroup); }
return dataGroups;
}
});
Template:
<template name="example">
<div class='panel panel-default'>
<ul class='list-group'>
{{#each itemsGrouped}}
{{#if group}}
<li class="list-group-item">
<a data-toggle="collapse" data-target="#{{tag}}"> Items tagged {{tag}}</a>
</li>
<div id="{{tag}}" class="collapse">
{{#each items}}
<li class='list-group-item'>{{name}}</li>
{{/each}}
</div>
{{else}}
<li class='list-group-item'>{{name}}</li>
{{/if}}
{{/each}}
</ul>
</div>
</template>
If you log the value you are returning from the eachItem helper, you will see you are not closing the last div element. Fixing that may get it working again. However, you have div elements as direct children of the ul element, which you are not supposed to according to the HTML5 specification:
Permitted contents: Zero or more li elements
Also, I think it would be a better option for you to prepare your context in a format that makes it easier to let simple templates take care of the rendering. For example, using the same data from your jsfiddle, suppose you had it in the following format:
tagGroups = [{
names: ["item1", "item2"]
},{
tag: "red",
names: ["item3", "item4"]
},{
tag: "blue",
names: ["item5", "item6", "item7"]
}]
The following templates would give you the expected result in a valid html format. The ending result is a bootstrap panel containing collapsible list-groups:
<template name="accordion">
<div class="panel panel-default">
{{#each tagGroups}}
{{> tagGroup}}
{{/each}}
</div>
</template>
<template name="tagGroup">
{{#if tag}}
{{> namesListCollapse}}
{{else}}
{{> namesList}}
{{/if}}
</template>
<template name="namesList">
<ul class="list-group">
{{#each names}}
<li class="list-group-item">{{this}}</li>
{{/each}}
</ul>
</template>
<template name="namesListCollapse">
<div class="panel-heading"><a data-toggle="collapse" data-target="#{{tag}}">Items tagged {{tag}}</a></div>
<ul id="{{tag}}" class="panel-collapse collapse list-group">
{{#each names}}
<li class="list-group-item">
{{this}}
</li>
{{/each}}
</ul>
</template>
And here is an example of a helper to transform your data so you can make a quick test to see it working:
Template.accordion.tagGroups = function () {
var data = [{
name : 'item1'
},{
name : 'item2'
},{
name : 'item3',
tag : 'red'
},{
name : 'item4',
tag : 'red'
},{
name : 'item5',
tag : 'blue'
},{
name : 'item6',
tag : 'blue'
},{
name : 'item7',
tag : 'blue'
}];
data = _.groupBy(data, 'tag');
data = _.map(data, function (value, key) {
var obj = {};
if (key !== 'undefined') {
obj.tag = key;
}
var names = _.map(value, function (item) {
return item.name;
});
obj.names = names;
return obj;
});
//console.dir(data);
return data;
};
And yes, if the items come from a collection, you will get reactivity by default.

Meteor + Iron Router to create breadcrumbs

Ok, so I found this post: Meteor breadcrumb
But lets say I have the following:
<template name="somePage">
<h1>Page Title</h1>
{{> breadcrumb}}
</template>
<template name="breadcrumb">
<ul class="breadcrumb">
<li>
Home
</li>
{{#each path}}
<li>
{{this}}
</li>
</ul>
</template>
Helper:
Template.breadcrumb.helpers({
path: function() {
return Router.current().path.split( "/" );
}
});
Ok so the linked question at the top got me the basics. I'm trying to understand how to do a few more things here that should be obvious. I want the first to be for the home page, and the result returned from the path: function() includes an empty "", "page", "page", etc. in the beginning of it.
I'd like to be able to incorporate the proper paths. To be clear, I'd love to pull this off:
<template name="breadcrumb">
<ul class="breadcrumb">
<li>
Home
</li>
~ pseudo logic
{{#each path that isn't current page}}
<li>
{{this}}
</li>
{{/each}}
<li>
{{ currentPage }}
</li>
</ul>
</template>
Has anyone done this or found a reference that I haven't stumbled across yet?
I'll give you my own recipe for breadcrumbs using iron:router.
It works by supplying additional options to your routes in order to establish a hierarchy between them, with parent-children relations. Then we define a helper on the Router to give us a list of parent routes (up to home) for the current route. When you have this list of route names you can iterate over them to create your breadcrumbs.
First, we need to define our breadcrumbs template which is actually very similar to your pseudo-code. I'm using bootstrap and font-awesome, as well as some newly introduced iron:router#1.0.0-pre features.
<template name="breadcrumbs">
<ol class="breadcrumb">
<li>
{{#linkTo route="home"}}
<i class="fa fa-lg fa-fw fa-home"></i>
{{/linkTo}}
</li>
{{#each intermediateRoutes}}
<li>
{{#linkTo route=name}}
<strong>{{label}}</strong>
{{/linkTo}}
</li>
{{/each}}
<li class="active">
<strong>{{currentRouteLabel}}</strong>
</li>
</ol>
</template>
The {{#linkTo}} block helper is new in iron:router#1.0.0-pre, it simply outputs an anchor tag with an href attribute which value is {{pathFor "route"}}.
Let's define the helpers from our breadcrumbs template:
Template.breadcrumbs.helpers({
intermediateRoutes: function() {
if (!Router.current()) {
return;
}
// get rid of both the first item, which is always assumed to be "home",
// and the last item which we won't display as a link
var routes = Router.parentRoutes().slice(1, -1);
return _.map(routes, function(route) {
// extract name and label properties from the route
return {
name: route.getName(),
label: route.options.label
};
});
},
currentRouteLabel: function() {
// return the label property from the current route options
return Router.current() && Router.current().route.options.label;
}
});
Notice that we rely on the existence of a special option named 'label' which represents what we're going to put in our anchors, we could also have used the name for testing purpose.
The parentRoutes method is something we need to extend the Router with:
_.extend(Router, {
parentRoutes: function() {
if (!this.current()) {
return;
}
var routes = [];
for (var route = this.current().route; !_.isUndefined(route); route = this.routes[route.options.parent]) {
routes.push(route);
}
return routes.reverse();
}
});
Again, this function assumes that every route (except "home") has a parent property which contains the name of its parent route, we then iterate to traverse the route hierarchy (think of a tree, like a file system structure) from the current route up to the root route, collecting each intermediate route in an array, along with the current route.
Finally, don't forget to declare your routes with our two additional properties that our code relies on, along with a name which is now mandatory as routes are indexed by name in the Router.routes property:
Router.route("/", {
name: "home"
});
Router.route("/nested1", {
name: "nested1",
parent: "home"
});
Router.route("/nested1/nested2", {
name: "nested2",
parent: "nested1"
});
// etc...
This example is pretty basic and certainly doesn't cover every use case, but should give you a solid start in terms of design logic toward implementing your own breadcrumbs.
Inspired by #saimeunt I created a meteor breadcrumb plugin which can be found here: https://atmospherejs.com/monbro/iron-router-breadcrumb. You also specify a parent route and a title for the route itself.
I used saimeunt answer but had to make small changes to the template and the template helpers because I have parameters in some of my route paths. Here are my changes.
Template changes: add data=getParameter to #linkTo for intermediate routes
<template name="breadcrumbs">
<ol class="breadcrumb">
<li>
{{#linkTo route="dashboard"}}
<i class="fa fa-lg fa-fw fa-home"></i>
{{/linkTo}}
</li>
{{#each intermediateRoutes}}
<li>
{{#linkTo route=name data=getParameters}}
<strong>{{label}}</strong>
{{/linkTo}}
</li>
{{/each}}
<li class='active'>
<strong>{{currentRouteLabel}}</strong>
</li>
</ol>
</template>
Template helper changes: add helper function getParameters to get parameters from current route.
Template.breadcrumbs.helpers({
intermediateRoutes: function () {
if (!Router.current()) {
return;
}
var parentRoutes = Router.parentRoutes();
var routes = parentRoutes.slice(1, -1);
var intermediateRoutes = _.map(routes, function (route) {
return {
name: route.getName(),
label: route.options.label
};
});
return intermediateRoutes;
},
currentRouteLabel: function () {
var currentRouteLabel = Router.current() && Router.current().route.options.label;
return currentRouteLabel;
},
getParameters: function(){
var currentRoute = Router.current();
var parameters = currentRoute.params;
return parameters;
}
});

Resources