Why are Vue dynamic components destroyed inside loop every re-render? - vue.js

I run into an issue with Vuejs 2.x version (latest). While rendering a list of item inside a loop, if I make changes to the items then the normal components are not destroyed but the dynamic components will always be destroyed:
I have put a short sample code here:
https://gist.github.com/yellow1912/fc1c053e07c1ca136148484cf7f79d1a
I have also put a codepen here:
https://codepen.io/raineng/pen/zYGOXYY?editors=1111
<nl-test inline-template>
<div>
<div v-on:click="increase"> increase here please </div><br><br>
<div v-on:click="decrease"> decrease here please </div>
<ul>
<li v-for="(value, key) in getItems()" :key="key">
printing
<component :is="getItem()" :key="key"></component>
<nl-test inline-template>
<div>
this is a test here
</div>
</nl-test>
</li>
</ul>
</div>
</nl-test>
To see what I mean, open the console tab on codepen, click the add item and you will see that the dynamic component items are destroyed and re-created everytime.

I found out why, I need to use keep-alive:
https://v2.vuejs.org/v2/guide/components-dynamic-async.html
To quote:
When switching between these components though, you’ll sometimes want
to maintain their state or avoid re-rendering for performance reasons
Recreating dynamic components is normally useful behavior, but in this
case, we’d really like those tab component instances to be cached once
they’re created for the first time. To solve this problem, we can wrap
our dynamic component with a element
Wasted 2 days on this issue and then I found the answer just a moment after posting this on StackOverflow. Hope it helps someone.

Related

Vue: communicating parameters from app to component and back, using computed properties

Sorry for the beginner question (I'm fairly sure this will be a duplicate, but I actually can't figure out what terms to use in order to find it). I just started with Vue.
I am just getting started with Vue, and following this course (https://www.vuemastery.com/courses/intro-to-vue-js/communicating-events). In this problem, there is (and here I don't know the term, so I'm going to go with...) app-level data parameter called cart. cart is an array which holds the id of each item a user has added to cart.
The problem tells us to add a button to remove items from the cart.
I ran into problems trying to create a computed property, which would allow me to hide the "remove" button in the event the selected item is not in the cart (eg. `
Communicating data from the app-level (the cart array), to the component-level (to a computed property in the product component), so that I could use something like :hidden="!inCart" on the "Remove from Cart" button, which is itself defined in the component. inCart would be a computed value here.
Communicating the selected product from the component to the app-level, computing inCart at the app level, then using the computed value at the component-level.
Either way, I can't seem to figure out how to do this in the way I would want to, which would look something like how v-bind operates. Namely, I think I may be able to hack together a solution using methods (which I believe have to be triggered by certain events), but I don't understand how I might go about this using built-in functionality such that the value of inCart is dynamically auto-computed.
Maybe there would be an answer to this in the next few courses, but I don't see us covering that in the intro material. Sorry for the neophyte question. Thank you in advance.
In Vue the way you communicate "state" from higher-level objects to lower-level objects is through props.
So, assuming your app looks something like...
<MyApp>
<MyShoppingPageWithItems>
<MyItem></MyItem>
<MyItem></MyItem>
<MyShoppingPageWithItems>
</MyApp>
You need to pass the cart object down as a prop.
So in your MyShoppingPageWithItems template, you'll have something like...
<template>
<div>
<MyItem v-for="item in items" :item=item :cart="cart"?
</MyItem>
</div>
</template>
And in your item template...
<template>
<div>
<div>
{{item.name}}
</div>
<div v-if="cart.includes(item.id)">
Remove button or whatever
</div>
</div>
</template>
Not that the .includes() method is a native JavaScript method, which you can read more about here.
Edit
To reference a prop in a computed property (or anywhere else in a Vue component), just refer to this.propName, as demonstrated here in the Vue docs.
So, if you want to create a computed property, you can do the following:
<template>
<div>
<div>
{{item.name}}
</div>
<div v-if="isInCart">
Remove button or whatever
</div>
</div>
</template>
<script>
export default {
props: ['cart', 'item'],
computed: {
isInCart() {
return this.cart.includes(this.item.id)
}
}
}
</script>
Note that the formula is the exact same as above, but just includes this. for cart and item. In templates, the this. is implied when referring to props, data, and computed properties.

VueJS: <template> vs <div> or related for grouping elements for conditional rendering

In Vue.js, if you want to conditionally render multiple elements via a v-if/v-else-if directive you can wrap them inside <template> tags and apply the directive to the <template> tag, as explained here. However, you can also do the same with <div> tags wrapping the multiple elements. Are there any noticeable performance benefits to using <template> over <div> or any other similar native HTML5 tag?
I doubt there is a performance change but a big difference is that the <template> node does not appear in the DOM.
This is an important distinction especially when grouping children that are the only valid node types for their parent such as list items, table rows, etc:
This is valid:
<ul>
<template v-if="something">
<li>Text</li>
<li>Text</li>
</template>
</ul>
This is not:
<ul>
<div v-if="something">
<li>Text</li>
<li>Text</li>
</div>
</ul>
I know that the question is quite old, but I found out one more thing
if you use divs - your div will be in DOM, but empty, if v-if is false and it can make some spaces looks like margins
if you use template - you don't have anything in DOM and it just don't appear

Vuejs computed properties and jquery ui sortable issue

In my project I have a component with three ul lists. Also I have some kind of data array with items, each item has some properties. My aim is to:
Distribute items in basic array into three lists
Make it possible to drag&drop items between lists and accordingly update items data, since each item has a property which tells us which list the item belongs
Instead of copy-pasting a lot of code, I tried to reproduce the incorrect behaviour in jsfiddle by using simple example here:
https://jsfiddle.net/89pL26d2/4/
The thing is, when you drag&drop, you got exactly 2 items dragged, instead of one.
However, when I switched from computed properties to watch, I got the desired behaviour and everything worked just fine.
I figure out which line causes the error: the line when I update item property telling me which list the item should belong to after drag is finished. But I can't figure out why it causes this
I know that it's not the best way to work with HTML directly, but I'm okay with that for now.
Generally, whenever I see an issue in Vue, especially related to lists, where the wrong item is updated or something like that, it comes down to Vue trying to be smart but getting it wrong because it doesn't have the best information. This is almost always solved by using a key.
It is recommended to provide a key with v-for whenever possible,
unless the iterated DOM content is simple, or you are intentionally
relying on the default behavior for performance gains.
Key.
<div id="app">
<div>
<ul id="listA" data-list="A" class="connectedSortable">
<li v-for="item in listAFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li>
</ul>
<ul id="listB" data-list="B" class="connectedSortable">
<li v-for="item in listBFiltered" :key="item.id" :data-id="item.id">{{ item.title }}</li>
</ul>
</div>
</div>
Adding a key fixes your issue.

easy durandal please wait while loading spinner

Is there an easy durandal way to clear the view and put a loading or please wait... on the screen so the user gets some feedback to know that it is working until the ajax content loads?
Right now when I click on a something that navigates to a child route and that child route loads a module that has to do a lot of stuff in activate(), it does not switch the nav or clear the screen or give any feedback to the user that it is working and I see them clicking many times over and over and getting frustrated, then just about when they want to give up, the page loads in fine.
I would like to make this default functionality for my app and not have to do something special in every module or on every page, is that possible?
Thanks.
Have you tried to use router.isNavigating? Original Durandal template contains a spinner like this:
<div class="loader pull-right" data-bind="css: { active: router.isNavigating }">
<i class="icon-spinner icon-2x icon-spin"></i>
</div>
A large percentage of the time, what you're looking for can be obtained very simply via:
<div data-bind="compose:ActiveVm">
<div class="text-center" style="margin : 75px">
<i class="fa fa-spinner fa-spin"></i>
</div>
</div>
The inner div can be any arbitrary markup which will display while the viewmodel is going through activation.
Note that this currently only displays the placeholder content the first time this dom section is composed. If you have a section of your application which is being updated via an observable viewmodel + compose approach, you could use the approach here:
Durandal: Showing a 'LOADING...' during composition
For anyone visiting from the future, this issue might be worth checking out in case native support for this is desired:
https://github.com/BlueSpire/Durandal/issues/414

Good way to integrate query-layout with reactive templates + async data sources?

I'm working on a Meteor app that gets data from Facebook & I would like to use jquery-layout for presentation. I suspected that there might be some "subtleties" when trying to use jquery to modify HTML in reactive templates, so I set up a relatively simple test case that goes something like this (paraphrased for brevity)...
<body>
{{> mainTemplate}}
</body>
<template name="mainTemplate">
{{#with userInfo}}
{{> partialNorth}}
{{> partialWest}}
{{> partialCenter}}
{{> partialEast}}
{{/with}}
{{layItOut}}
</template>
Template.mainTemplate.userInfo returns contents of a Session variable that starts with a default value and asynchronously get updated with info from Facebook.
Template.mainTemplate.layItOut sets up a call to Meteor.defer with a callback fcn that actually executes the 5 lines of jquery-layout code.
And that seems to work pretty well...
the initial display is as expected/intended (although there's a brief period where the page is not laid out)
any updates to the reactive context cause re-execution of the layout (again, w/brief-but-visible re-layout)
So, why am I whining? Mostly I would like to find a cleaner approach that does away with the noticeable re-layout activity.
I could make the reactive contexts more granular, but I'm not sure that this would really help.
Alternatively, I suppose I could experiment with directly controlling rendering (e.g., via Meteor.ui.render() , but that sounds like a lot of work ;-)
I think what I'd really like is either
a) a way to hook into Meteor render events
or better still
b) a cleaner way to connect query-layout to templates
Thoughts?
So I managed to educate myself enough to answer my own question in case anyone else finds it useful. Bottom line is that I was wrong on several levels; making the reactive contexts more granular is the answer (or at least an answer).
In the example I gave, I made the whole page reactive by placing all of the rendering within the #each construct. What I now do is try to make the reactive contexts as small as possible so that only a (relatively) small part of the page is re-rendered on any reactive change and all of the reactive elements are contained below (or way below) the level of the jquery ui elements.
I.e., something like this:
<body>
{{> mainTemplate}}
</body>
<template name="mainTemplate">
{{#with userInfo}}
{{> partialNorth}}
{{> partialWest}}
...
{{/with}}
{{layItOut}}
</template>
<template name="partialNorth">
<div class="ui-layout-north"> <-- definition for jquery-layout north panel
<h1>This is the north pane</h1>
<p>The user data go next:</p><br />
{{> templateUserData}}
</div>
</template>
<template name="templateUserData">
<div>
{{#with theUserData}} <-- Assumes a helper function 'theUserData' for this template
<p>First name: {{first_name}}</p>
<p>Last name: {{last_name}}</p>
...
{{/with}}
</div>
</template>
Once you have the reactive elements below the jquery ui elements (I have tried it with panels, tabs, accordions, buttons and pop-ups so far) the whole thing works just like it said it would in the shiny brochure! ;-)