I am wondering if refreshing a page that runs a Vue app will trigger the Vue's .destroyed callback.
From what I observed in a Vue app that contains these simple lifecycle callbacks:
created() {
console.log(' created');
},
destroyed() {
console.log('destroyed');
}
only 'created' is logged (not 'destroyed'). How can I check if the .destroyed callback has been executed?
I found the similar question and answer to it on stackoverflow
Do something before reload or close in vue.js
He/she basically explains that nothing is destroyed on page reload, you need to define
window.onbeforeunload = function(){
return "Are you sure you want to close the window?";
}
If you want to do something before a page refresh
As your question was
Is Vue's 'destroyed' method called on page refresh?
No, destroyed method called if your component's controller lost or you manually destroy, above example is for manually destroy.
I have found very good example in vuejs forum which uses externally this.$destroy() method.
new Vue({
el: '#app',
data() {
return {
value: 'will work until destroy'
};
},
methods: {
destroy() {
this.$destroy();
}
},
beforeDestroy() {
console.log('Main Vue destroyed')
}
})
var tmp = Vue.extend({
template: `
<div>
<span>{{ value }}</span>
<input v-model="value" />
</div>
`,
data() {
return {
value: 'always bind and work'
};
},
beforeDestroy() {
console.log('Mounted destroyed')
}
});
new tmp().$mount('#mount-point');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
{{ value }}
<input v-model="value" />
<div id="mount-point"></div>
<button #click="destroy()">Destroy</button>
</div>
Reference
Another example. If component's control lost or removed then destroy method will be called of that component's
Vue.component('comp1', {
template: '<div>A custom component1!</div>',
destroyed(){
console.log('comp1 destroyed');
}
})
Vue.component('comp2', {
template: '<div>A custom component2!</div>',
destroyed(){
console.log('comp2 destroyed');
}
})
new Vue({
el: '#app',
data() {
return {
value: 1
};
},
methods: {
},
beforeDestroy() {
console.log('Main Vue destroyed')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
<select v-model="value">
<option value="1">comp1</option>
<option value="2">comp2</option>
</select>
<comp1 v-if="value==1"></comp1>
<comp2 v-if="value==2"></comp2>
<button #click="destroy()">Destroy</button>
</div>
Related
If you click the button, you can see the value of state updated in the console, but it isn't updated in the page output. How can I make it work with a default injected value?
const Component = {
inject: {
state: {
default: () => ({
example: 1
})
}
},
template: `<div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
components: {
Component
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component></component>
</div>
Is it related to as Vue docs say "Note: the provide and inject bindings are NOT reactive. This is intentional. However, if you pass down an observed object, properties on that object do remain reactive."? I'm confused about the difference between the BINDINGS not being reactive but the OBSERVED OBJECT being reactive. Could you show an example to demo the difference?
Sorry, but it is not clear what you want - where's the provider for the "injection"? Why do you use inject in the same component as you use the value itself?
Here's your code, without inject:
1. Use the data attribute
const Component = {
data() {
return {
state: {
example: 1
}
}
},
template: `<div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
components: {
Component
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component></component>
</div>
Just use the data attribute - you can have a default value for example.
2. Use injection
inject is something completely different - it's a way to pass values from a provider to a consumer:
const Component = {
inject: ['state1'],
data() {
return {
state: {
example: 1
}
}
},
template: `<div>
<div>injected: {{ state1 }}</div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
provide: {
state1: {
example1: 1
}
},
components: {
Component
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component></component>
</div>
You can "skip" levels of components and use the provided value in components where you inject it - you don't have to pass it all the way down as props.
3. Create reactive inection
If you want to have reactive injection then you need to pass down something more complex:
const Component1 = {
inject: ['state2'],
data() {
return {
state: {
example: 1
}
}
},
template: `<div>
<div>injected: {{ state2.state2P }}</div>
<div>{{ state }}</div>
<button #click="click">click</button>
</div>`,
methods: {
click() {
this.state.example += 1
console.log(this.state)
}
}
}
new Vue({
el: "#app",
data() {
return {
state2: {
example2: 1
}
}
},
provide() {
// create an object (state2)
const state2 = {}
// define a property on the object (state2P), that
// has a get() function that always gets the provider's
// value you want to inject
Object.defineProperty(state2, 'state2P', {
enumerable: true,
get: () => this.state2,
})
// return the created object (with a property that always
// gets the value in the parent)
return {
state2
}
},
components: {
Component1
},
methods: {
parentClick() {
this.state2.example2 += 1
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<component1></component1>
<button #click="parentClick">PARENT CLICK</button>
</div>
I added a button to the template, so you can see that a method defined in the provider component's scope changes the value displayed in the consumer component's scope. (Also had to change the component's name, as Vue started to "whine" about using a restricted word.)
I would like to listen to all focus events on inputs accross my Vue application.
To get the currently focused input, I thought about binding the document.activeElement property to a computed property in my app component, but this is not reactive, why ?
Declaring the activeElement in the data is not reactive either.
Same thing for watchers !
The only way to get it working is by simply returning the value after a focus/blur event on the input itself, but that doesn't suit my needs here.
new Vue({
el: "#app",
data: {
activeElem: document.activeElement.tagName,
realActiveElem: document.activeElement.tagName,
},
methods: {
getActiveElem() {
this.realActiveElem = document.activeElement.tagName;
}
},
computed: {
focused() {
return document.activeElement.tagName;
}
},
watch: {
activeElem(val, oldVal) {
console.log(val !== oldVal);
},
focused(val, oldVal) {
console.log(val !== oldVal);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h2 #focus="getActiveElem()">
Data: {{activeElem}}
</h2>
<h2>
Computed: {{focused}}
</h2>
<h2>
From function to data: {{realActiveElem}}
</h2>
<input placeholder="Focus/Blur me" id="test" #focus="getActiveElem()" #blur="getActiveElem()" />
</div>
Is there any way to bind document or window properties as reactive ?
Vue can only react to changes made to data, not to the DOM. The change in document.activeElement is a DOM change.
You could use use an event to fire a method to update data. For example:
new Vue({
el: "#app",
data: {
element: ""
},
created() {
document.addEventListener("focusin", this.focusChanged);
},
beforeDestroy() {
document.removeEventListener("focusin", this.focusChanged);
},
methods: {
focusChanged(event) {
this.element = event.target.tagName;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input id="mine">
<p>{{ element }}</p>
</div>
My app consists of:
A component named
<consl :output="output" #submit-to-vue><consl>
which contains an input that calls a submit() method when enter key is pressed.
<div>
<output v-html="output"></output>
<div id="input-line" class="input-line">
<div class="prompt">{{ prompt }}</div>
<div>
<input class="cmdline" autofocus
v-model.trim="command"
#keyup.enter="submit"
:readonly="submited" />
</div>
</div>
Then the method submit() emits an event #submit-to-vue to parent method submitv() that create an instance of the same component and adds it to the DOM.
//........
methods: {
submit: function () {
this.$emit('submit-to-vue')
this.submited = true
}
},
and
//......
methods: {
submitv: function () {
var ComponentClass = Vue.extend(consl)
var instance = new ComponentClass({
propsData: { output: this.output }
})
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)
What I want to accomplish ?
I want to create a new consl component and add it to the DOM every time the old one is submited. (I want my app to emulate a terminal)
The problem
When submitted the new created component does not contain the #submit-to-vue event listener, which make it unable to recall the submitv() method.
Questions
How can I solve this problem ?
Is this the proper way to do things in VueJs or is there a more elegent way ?
In parent component, declare one data property=childs, it will includes all childs already created.
So once parent component receives the event=submit-to-vue, then add one new child to this.childs
Finally uses v-for to render these child components.
The trick: always consider the data-driven way, doesn't manipulate dom directly as possible.
below is one simple demo :
Vue.config.productionTip = false
Vue.component('child', {
template: `
<div>
<div>Label:<span>{{output}}</span></div>
<div>Value:<span>{{command}}</span></div>
<div id="input-line" class="input-line">
<div class="prompt">{{ prompt }}</div>
<div>
<input class="cmdline" autofocus
v-model.trim="command"
#keyup.enter="submit"
:readonly="submited" />
</div>
</div>
</div>`,
props: ['output'],
data() {
return {
submited: false,
command: ''
}
},
computed: {
prompt: function () {
return this.submited ? 'Already submitted, input is ready-only now' : ''
}
},
methods: {
submit: function () {
this.$emit('submit-to-vue')
this.submited = true
}
}
})
app = new Vue({
el: "#app",
data: {
childs: [{'output':'default:'}]
},
methods: {
addChild: function () {
this.childs.push({'output': this.childs.length})
}
}
})
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<div>
<ul>
<li v-for="(child, index) in childs" :key="index">
<child :output="child.output" #submit-to-vue="addChild()"></child>
</li>
</ul>
</div>
</div>
Can I pass in a template string and also dynamically pass in a property so that I can make it reactive? In the example below I would like message to be reactive, but I don't want to have to predefine it on the data option.
<div id="vue">
<component :is="string && {template:string}"/>
</div>
new Vue({
el:'#vue',
data(){
return {
string:undefined,
}
},
created(){
//setTimeout to simulate ajax call
setTimeout(()=> this.string = '<div><h1 v-for="n in 1">Hello! </h1><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p> </div>', 1000)
}
})
https://jsfiddle.net/kxtsvtro/5/
You can specify the data in the same way you specify the template: just interpolate it into the component spec.
new Vue({
el: '#vue',
data() {
return {
string: undefined,
dataObj: undefined
}
},
created() {
//setTimeout to simulate ajax call
setTimeout(() => {
this.string = '<div><h1 v-for="n in 1">Hello!</h1><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p></div>';
this.dataObj = {
message: 'initial'
};
}, 1000)
}
})
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="vue">
<component :is="string && {template:string, data: function() { return dataObj}}" />
</div>
It looks like what you want is a component with a <slot> that you can dump a custom component into. If you're trying to compose components that's probably the easiest way to do it.
You can use Props, but I am not sure if this is the best way to do it :) here is an example:
new Vue({
el:'#vue',
data(){
return {
string:undefined,
message:''
}
},
created(){
//setTimeout to simulate ajax call
setTimeout(()=> this.string = '<div><h1 v-for="n in 1">Hello!</h1><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p></div>', 1000)
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.min.js"></script>
<div id="vue">
<component :is="string && {template:string, props:['message']}" :message="message"/>
</div>
in my vuejs program i am trying to make a global instance of an alert/notification system. This would be at the rootmost instance of the app. and then my plan was to push to an array of objects and pass that through to the component.
This only half works.
in my app.vue i have
<template>
<div id="app">
<alert-queue :alerts="$alerts"></alert-queue>
<router-view></router-view>
</div>
</template>
in my main.js i have
exports.install = function (Vue, options) {
Vue.prototype.$alerts = []
}
and my alert_queue.vue is
<template>
<div id="alert-queue">
<div v-for="alert in alerts" >
<transition name="fade">
<div>
<div class="alert-card-close">
<span #click="dismissAlert(alert)"> × </span>
</div>
<div class="alert-card-message">
{{alert.message}}
</div>
</div>
</transition>
</div>
</div>
</template>
<script>
export default {
name: 'alert',
props: {
alerts: {
default: []
}
},
data () {
return {
}
},
methods: {
dismissAlert (alert) {
for (let i = 0; i < this.alerts.length; i++) {
if (this.alerts[i].message === alert.message) {
this.alerts.splice([i], 1)
}
}
}
}
}
</script>
I can add to this list now by using this.$alerts.push({}) and i can see they are added by console.logging the results.
The problem is that the component doesn't recognise them unless i manually go in and force it to refresh by changing something in code and having webpack reload the results. as far as i can see, there is no way to do this programatically.... Is there a way to make prototype components be watched like the rest of the application?
I have tried making the root most file have a $alerts object but when i use $root.$alerts.push({}) it doesn't work because $root is readonly.
Is there another way i can go about this ?
You could make $alerts a Vue instance and use it as an event bus:
exports.install = function (Vue, options) {
Vue.prototype.$alerts = new Vue({
data: {alerts: []},
events: { ... },
methods: { ... }
})
}
Then in your components you might call a method this.$alerts.addAlert() which in turn pushes to the array and broadcasts an event alert-added. In other places you could use this.$alerts.on('alert-added', (alert) => { ... }
Other than that, I think this is a good use case for Vuex, which is pretty much designed for this: https://github.com/vuejs/vuex
Properties defined on Vue.prototype are not reactive like a Vue instance's data properties.
I agree that, in most cases, Jeff's method or using Vuex is the way to go.
However, you could simply set this.$alerts as a Vue instance's data property and then updating that property (which would be reactive) would, by association, update the global $alerts array:
Vue.prototype.$alerts = ['Alert #1'];
Vue.component('child', {
template: `<div><div v-for="i in items">{{ i }}</div></div>`,
props: ['items'],
})
new Vue({
el: '#app',
data() {
return {
globalAlerts: this.$alerts,
}
},
methods: {
addToArray() {
this.globalAlerts.push('Alert #' + (this.globalAlerts.length + 1));
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.min.js"></script>
<div id="app">
<child :items="$alerts"></child>
<button #click="addToArray">Add alert</button>
</div>