Cannot access element shown by v-if in component mounted callback - vue.js

<template>
<div>
<transition name="fade" mode="out-in">
<div class="ui active inline loader" v-if="loading" key="loading"></div>
<div v-else key="loaded">
<span class="foo" ref="foo">the content I'm after is here</span>
</div>
</transition>
</div>
</template>
<script>
export default {
data() {
return {
loaded: false
}
},
mounted() {
setTimeout(() => { // simulate async operation
this.loaded = true
console.log($(this.$refs.foo).length, $(this.$el.find('.foo')).length)
}, 2000)
},
}
</script>
Regardless if I use this.$refs or this.$el, I'm only able to access the loader div (<div class="ui active inline loader"/>).
How am I supposed to access an element which doesn't exist when the component is mounted? Do I have to change v-if to v-show?

Vue renders to the DOM asynchronously. So, even though you are setting your loaded property to true, the ref will not exist until the next tick in Vue's cycle.
To handle that, use the $nextTick method.
console.clear()
new Vue({
el: "#app",
data:{
loading: true
},
mounted(){
setTimeout(()=> {
this.loading = false
this.$nextTick(() => console.log(this.$refs.done))
}, 1000)
}
})
<script src="https://unpkg.com/vue#2.4.2"></script>
<div id="app">
<div v-if="loading">Loading</div>
<div ref="done" v-else>Done</div>
</div>
Additionally, in the question, the v-if expression is loading which will always be undefined because the data property is called loaded.

Related

vue NOT re render with data change

Vue renders v-if=true. But if I change bool true to false,
vue doesn't re-render to v-else div.
How should it be? Is there any way to re-render?
Here is my code:
<template>
<div v-if="bool">
true
</div>
<div v-else>
false // if button pressed, i should be shown!!!!
</div>
<button :click='onClickEvent()'>click!!!!!!</button>
</template>
<script>
export default {
data: function () {
return {
bool: true
};
},
created() {
},
mounted(){
}
methods: {
onClickEvent: function(){
this.bool= false
}
}
};
</script>
I tried everything I could think of.
You should not be binding with :click instead it should be #click="onClickEvent".
https://vuejs.org/guide/essentials/event-handling.html

Only show slot if it has content, when slot has no name?

As answered here, we can check if a slot has content or not. But I am using a slot which has no name:
<template>
<div id="map" v-if="!isValueNull">
<div id="map-key">{{ name }}</div>
<div id="map-value">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
name: {type: String, default: null}
},
computed: {
isValueNull() {
console.log(this.$slots)
return false;
}
}
}
</script>
I am using like this:
<my-map name="someName">{{someValue}}</my-map>
How can I not show the component when it has no value?
All slots have a name. If you don't give it a name explicitly then it'll be called default.
So you can check for $slots.default.
A word of caution though. $slots is not reactive, so when it changes it won't invalidate any computed properties that use it. However, it will trigger a re-rendering of the component, so if you use it directly in the template or via a method it should work fine.
Here's an example to illustrate that the caching of computed properties is not invalidated when the slot's contents change.
const child = {
template: `
<div>
<div>computedHasSlotContent: {{ computedHasSlotContent }}</div>
<div>methodHasSlotContent: {{ methodHasSlotContent() }}</div>
<slot></slot>
</div>
`,
computed: {
computedHasSlotContent () {
return !!this.$slots.default
}
},
methods: {
methodHasSlotContent () {
return !!this.$slots.default
}
}
}
new Vue({
components: {
child
},
el: '#app',
data () {
return {
show: true
}
}
})
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<button #click="show = !show">Toggle</button>
<child>
<p v-if="show">Child text</p>
</child>
</div>
Why you dont pass that value as prop to map component.
<my-map :someValue="someValue" name="someName">{{someValue}}</my-map>
and in my-map add prop:
props: {
someValue:{default: null},
},
So now you just check if someValue is null:
<div id="map" v-if="!someValue">
...
</div

Vue modal component using in parent component

I'm building simple modal component with Vue. I want to use this component in a parent components and to be able to toggle it from the parent.
This is my code now of the modal component:
<script>
export default {
name: 'Modal',
data() {
return {
modalOpen: true,
}
},
methods: {
modalToggle() {
this.modalOpen = !this.modalOpen
},
},
}
</script>
<template>
<div v-if="modalOpen" class="modal">
<div class="body">
body
</div>
<div class="btn_cancel" #click="modalToggle">
<i class="icon icon-cancel" />
</div>
</div>
</template>
I use the v-if to toggle the rendering and it works with the button i created inside my modal component.
However my problem is: I don't know how to toggle it with simple button from parent component. I don't know how to access the modalOpen data from the modal component
Ok, let's try to do it right. I propose to make a full-fledged component and control the opening and closing of a modal window using the v-model in parent components or in other includes.
1) We need declare prop - "value" in "props" for child component.
<script>
export default {
name: 'Modal',
props: ["value"],
data() {
return {
modalOpen: true,
}
},
methods: {
modalToggle() {
this.modalOpen = !this.modalOpen
},
},
}
</script>
2) Replace your "modalToggle" that:
modalToggle() {
this.$emit('input', !this.value);
}
3) In parent components or other includes declare "modal=false" var and use on component v-model="modal" and any control buttons for modal var.
summary
<template>
<div v-if="value" class="modal">
<div class="body">
body
</div>
<div class="btn_cancel" #click="modalToggle">
<i class="icon icon-cancel" />
</div>
</div>
</template>
<script>
export default {
name: "Modal",
props: ["value"],
methods: {
modalToggle() {
this.$emit("input", !this.value);
}
}
};
</script>
Example:
Vue.component('modal', {
template: '<div v-if="value" class="modal"><div class="body">modal body</div><div class="btn_cancel" #click="modalToggle">close modal<i class="icon icon-cancel" /></div></div>',
props: ["value"],
methods: {
modalToggle() {
this.$emit('input', !this.value);
}
}
});
// create a new Vue instance and mount it to our div element above with the id of app
var vm = new Vue({
el: '#app',
data:() =>({
modal: false
}),
methods: {
openModal() {
this.modal = !this.modal;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div #click="openModal">Btn modal</div>
<modal v-model="modal"></modal>
</div>
With your current implementation I would suggest you to use refs
https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements
So in your parent component add ref="child" to modal (child) component and then open your modal by calling this.$refs.child.modalToggle()
You can use an "activator" slot
You can use ref="xxx" on the child and access it from the parent

I get error in console when use "v-if" directive. Infinite loop

After when I use v-if, I get a [Vue warn] in my console, no idea how to solve this problem.
[Vue warn]: You may have an infinite update loop in a component render function.
<template>
<div class="example-component">
<div class="spinner-box" v-if="loadComplete = !loadComplete">
<div class="spinner-inner">
<i class="fas fa-circle-notch fa-spin"></i>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'ExampleComponent',
data () {
return {
loadComplete: false
}
}
</script>
Change
v-if="loadComplete = !loadComplete"
To
v-if="!loadComplete"
Example
https://2ozkjp4vyp.codesandbox.io/
<template>
<div id="app">
<img width=200 src="./assets/logo.png">
<div class="loader" v-if="!loadComplete"></div>
<div v-else>
<p>asynchronous data from firebase</p>
<button #click="loadDataFromFirebase">Reload</button>
</div>
</div>
</template>
<script>
export default {
name: 'app',
data: () => ({
loadComplete: false
}),
mounted () {
this.loadDataFromFirebase()
},
methods: {
loadDataFromFirebase () {
this.loadComplete = false
setTimeout(() => {
this.loadComplete = true
}, 1000)
}
}
}
</script>
Just to clarify where the infinite update loop came.
The v-if="loadComplete = !loadComplete" is an assignment, where you are assigning the value !loadComplete to loadComplete. Whenever you assign a variable in Vue it will trigger a new render, and on the next render it is executing the same assignment again... and this result in an infinite loop.
#PaulTsai gave a great example using the correct way v-if="!loadComplete"

Move elements passed into a component using a slot

I'm just starting out with VueJS and I was trying to port over a simple jQuery read more plugin I had.
I've got everything working except I don't know how to get access to the contents of the slot. What I would like to do is move some elements passed into the slot to right above the div.readmore__wrapper.
Can this be done simply in the template, or am I going to have to do it some other way?
Here's my component so far...
<template>
<div class="readmore">
<!-- SOME ELEMENTS PASSED TO SLOT TO GO HERE! -->
<div class="readmore__wrapper" :class="{ 'active': open }">
<slot></slot>
</div>
Read {{ open ? lessLabel : moreLabel }}
</div>
</template>
<script>
export default {
name: 'read-more',
data() {
return {
open: false,
moreLabel: 'more',
lessLabel: 'less'
};
},
methods: {
toggle() {
this.open = !this.open;
}
},
}
</script>
You can certainly do what you describe. Manipulating the DOM in a component is typically done in the mounted hook. If you expect the content of the slot to be updated at some point, you might need to do the same thing in the updated hook, although in playing with it, simply having some interpolated content change didn't require it.
new Vue({
el: '#app',
components: {
readMore: {
template: '#read-more-template',
data() {
return {
open: false,
moreLabel: 'more',
lessLabel: 'less'
};
},
methods: {
toggle() {
this.open = !this.open;
}
},
mounted() {
const readmoreEl = this.$el.querySelector('.readmore__wrapper');
const firstEl = readmoreEl.querySelector('*');
this.$el.insertBefore(firstEl, readmoreEl);
}
}
}
});
.readmore__wrapper {
display: none;
}
.readmore__wrapper.active {
display: block;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id='app'>
Hi there.
<read-more>
<div>First div inside</div>
<div>Another div of content</div>
</read-more>
</div>
<template id="read-more-template">
<div class="readmore">
<!-- SOME ELEMENTS PASSED TO SLOT TO GO HERE! -->
<div class="readmore__wrapper" :class="{ 'active': open }">
<slot></slot>
</div>
Read {{ open ? lessLabel : moreLabel }}
</div>
</template>