I have a function that helps filter data. I am using v-on:change when a user changes the selection but I also need the function to be called even before the user selects the data. I have done the same with AngularJS previously using ng-init but I understand that there is no such a directive in vue.js
This is my function:
getUnits: function () {
var input = {block: this.block, floor: this.floor, unit_type: this.unit_type, status: this.status};
this.$http.post('/admin/units', input).then(function (response) {
console.log(response.data);
this.units = response.data;
}, function (response) {
console.log(response)
});
}
In the blade file I use blade forms to perform the filters:
<div class="large-2 columns">
{!! Form::select('floor', $floors,null, ['class'=>'form-control', 'placeholder'=>'All Floors', 'v-model'=>'floor', 'v-on:change'=>'getUnits()' ]) !!}
</div>
<div class="large-3 columns">
{!! Form::select('unit_type', $unit_types,null, ['class'=>'form-control', 'placeholder'=>'All Unit Types', 'v-model'=>'unit_type', 'v-on:change'=>'getUnits()' ]) !!}
</div>
This works fine when I select a specific item. Then if I click on all lets say all floors, it works. What I need is when the page is loaded, it calls the getUnits method which will perform the $http.post with empty input. In the backend I have handled the request in a way that if the input is empty it will give all the data.
How can I do this in vuejs2?
My Code: http://jsfiddle.net/q83bnLrx
You can call this function in the beforeMount section of a Vue component: like following:
// .....
methods: {
getUnits: function() { /* ... */ }
},
beforeMount() {
this.getUnits()
},
// ......
Working fiddle: https://jsfiddle.net/q83bnLrx/1/
There are different lifecycle hooks Vue provide:
I have listed few are :
beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
updated: Called after a data change causes the virtual DOM to be re-rendered and patched.
You can have a look at complete list here.
You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.
You need to do something like this (If you want to call the method on page load):
new Vue({
// ...
methods:{
getUnits: function() {...}
},
created: function(){
this.getUnits()
}
});
you can also do this using mounted
https://v2.vuejs.org/v2/guide/migration.html#ready-replaced
....
methods:{
getUnits: function() {...}
},
mounted: function(){
this.$nextTick(this.getUnits)
}
....
Beware that when the mounted event is fired on a component, not all Vue components are replaced yet, so the DOM may not be final yet.
To really simulate the DOM onload event, i.e. to fire after the DOM is ready but before the page is drawn, use vm.$nextTick from inside mounted:
mounted: function () {
this.$nextTick(function () {
// Will be executed when the DOM is ready
})
}
If you get data in array you can do like below. It's worked for me
<template>
{{ id }}
</template>
<script>
import axios from "axios";
export default {
name: 'HelloWorld',
data () {
return {
id: "",
}
},
mounted() {
axios({ method: "GET", "url": "https://localhost:42/api/getdata" }).then(result => {
console.log(result.data[0].LoginId);
this.id = result.data[0].LoginId;
}, error => {
console.error(error);
});
},
</script>
methods: {
methodName() {
fetch("url").then(async(response) => {
if (response.status === 200) {
const data = await response.json();
this.xy = data.data;
console.log("Success load");
}
})
}
}
you can do it using created() method. it will fire once page fully loaded.
created:function(){
this.fillEditForm();
},
Related
There is such a code:
<template>
<div class="wrapper">
</div>
</template>
<script>
import axios from 'axios';
export default{
created () {
console.log('222');
this.getTrackerIdData();
this.getTrackerData();
},
methods: {
getTrackerIdData () {
return axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=tracking_new.create" , {
})
.then(response => {
this.$store.commit('tracker/setTrackingKeyId', response.data.data.tracking_new_key_id);
this.$store.commit('tracker/setQrCodeUrl', response.data.data.filename_qr_code_tracking_new);
})
.catch(function (error) {
console.log(error);
});
},
getTrackerData () {
setInterval(()=>myTimer(this), 60000);
function myTimer(th) {
return axios.get("https://seo-gmbh.eu/couriertracker/json/couriertracker_api.php?action=get_tracking_data&key_id=" + th.$store.state.tracker.trackingKeyId , {
})
.then(response => {
th.$store.commit('tracker/setTrackingServerData', response.data.data.tracking_data);
})
.catch(function (error) {
console.log(error);
});
}
},
}
}
</script>
When starting such a solution in the project, the server-side developer informed me that at least the request method getTrackerIdData () on its side works twice!
Having placed the code (console.log ('222');) in the hook of the created lifecycle (where the method calls), I found that it is displayed twice in the firebug:
Question:
Why is this happening and what approach is right in this case from the point of view of the implementation of receiving data from the server?
P.S. If everything is called in the mounted hook, then the code works, including on the server side, only 1 time.
It is important to know that in any Vue instance lifecycle, only beforeCreate and created hooks are called both from client-side and server-side. All other hooks are called only from the client-side.
so thats why created hook called 2 times and executing the console.log ('222'); twice
for reference you can read from here
I have a Vue component that generates a dynamic component, and within that dynamic component is a click handler for a button that makes an Ajax call. Upon the Ajax call being successfully completed, I want to inform the component that generates the dynamic component that the Ajax call has finished. How do I do that?
The basic structure of the code in question is as follows:
<template>
<div>
<!-- Other markup here. -->
<div class="contentPlaceholder">
</div>
</div>
</template>
<script>
export default {
// Props, etc.
data: function () {
return {
// ...
content: 'long-html-string-that-contains-Vue-components'
};
},
mounted: function () {
Vue.component(`content-component`, {
template: `
<div class="content">
${this.content}
</div>
`,
data: function () {
return {
// Local data here.
};
}
methods: {
// Button in this.content markup clicked.
btnCicked: function () {
ajax.post('url', {
// Params
success: () => {
// Want to report back to the parent component
// that we're here now.
}
});
}
}
});
const res = Vue.compile(`
<content-component>
</content-component>
`);
new Vue({
render: res.render,
staticRenderFns: res.staticRenderFns
}).$mount(`.contentPlaceholder`);
}
}
</script>
My initial thought was to do this.$emit('btnClicked', 'data-here') in the Ajax success callback, but when I try to attach an #btnClicked event handler to the content-component in either the template part of the Vue.component method call or the Vue.compile method call, I get a Vue error.
Basically, I have no clue what to do. The this context is definitely different in the dynamic component, so I can't just add a data property to the parent component and then set it in the Ajax callback of the dynamic component. I tried that and it doesn't work.
I trust there is a simple way to do this, but I'm honestly not sure how. Any help would be greatly appreciated. Thank you.
Edit: It's worth noting that I tried to treat the dynamic component as if it were just a regular child component of the parent component. As such, I added a this.$emit('btnClicked') call within the Ajax success callback and then added an #btnClicked handler to the content-component, but it didn't work.
Maybe I'm just doing it wrong, but I tried both of the following:
template: `
<div class="content" #btnClicked="btnClicked">
${this.content}
</div>
`,
// And
const res = Vue.compile(`
<content-component #btnClicked="btnClicked">
</content-component>
`);
But neither seem to work. Thanks.
btnCicked: () => { console.log(this) }.
Try to use arrow function to save the context.
Another option is to create a function that already has access to outer this, and invoke it in your method.
const method = () => {
console.log('I have access to outer this', this)
}
...
btnCicked: function () { method(); console.log('Local this', this) }
...
I have the following:
Vue.component('times-updated', {
template: '<span>Times Updated: {{ timesUpdated }}</span>',
data: function() {
return {
timesUpdated: this.$parent.myData.timesUpdated
}
}
});
var vm = new Vue({
el: '#test',
data: function() {
return {
myData: {}
}
}
})
setInterval(function(){
$.ajax({
url: `${window.location.href}/json`, // This just returns an array : array.timesUpdated: 2 etc
}).done(function (data) {
vm.myData = data; // changes this data
});
}, 1000)
and am using the following html:
<div class="test">
<times-updated></times-updated>
</div>
I poll a REST API that returns an array which includes a timesUpdated property:
{
timesUpdated: 5
}
My intention is that every second I use jQuery's $.ajax method to call the API, update the myData data object on vm, which would then update the times-updated component.
The code works on initial page load, the times-updated component can retrieve the value on its parent's myData property, but whilst I have confirms that vm.myData does reflect the new value from the API, the component doesn't update its display to show the new count.
What am i doing wrong?
The data function is only called once during the life cycle of the component; when it is initially created. So essentially your component is just displaying the value as it existed when the component was created.
Additionally, it's generally bad practice to reach out of a component to get a data value. Vue is props down, events up. You should convert your component to use a property.
Vue.component('times-updated', {
props:["times"],
template: '<span>Times Updated: {{ times }}</span>',
})
The fact that you are using a function to define the Vue in this particular case doesn't really matter, it's just not a typical practice. Components require a function because they need an isolated scope.
Here is an example.
That callback is required only in components
// vue instance
new Vue({
data: {
status: true
}
};
// vue components (callback)
Vue.component('custom-component', {
data: function() {
return {
status: false
}
}
});
I am using Vue.Js v2. I want to call component1->c1method in component2->c2method for reload data after submitting.
Vue.component('component1', {
methods: {
c1method: function(){
alert('this is c1method')
},
}
})
Vue.component('component2', {
methods: {
c2method: function(){
component('component1').c1method()//like this
},
}
})
For non-parent-child relation, then this is the same as this one. Call one method, apparently any method of a component from any other component. Just add a $on function to the $root instance and call form any other component accessing the $root and calling $emit function.
On First component
....
mounted() {
this.$root.$on('component1', () => {
// your code goes here
this.c1method()
}
}
and in the second component call the $emit function in $root
...
c2method: function(){
this.$root.$emit('component1') //like this
},
It acts more like a socket. Reference here
https://stackoverflow.com/a/50343039/6090215
// Component A
Vue.component('A', {
created() {
this.$root.$refs.A = this;
},
methods: {
foo: function() {
alert('this is A.foo');
}
}
});
// Component B
Vue.component('B', {
methods: {
bar: function() {
this.$root.$refs.A.foo();
}
}
});
No need for hacky solutions.
In vuejs we can create events that can be listened globally.
With this feature, whenever we want to call our beloved function, we just emit this event.
Now, we just listen to this event all the time from the component. whenever this global event happens we can execute our method we want to call.
It's pretty simple:
you go to main.js, before creating the vue instance, write this:
export const eventBus = new Vue(); // added line
new Vue({
...
...
...
render: h => h(App)
}).$mount('#app');
Anywhere we want to fire the target function, we dont fire it, we just emit this event:
eventBus.$emit('fireMethod');
Now in our component that has the target function, we always listen to this event:
created() {
eventBus.$on('fireMethod', () => {
this.myBelovedMethod();
})
}
Dont forget to import eventBus in top.
import {eventBus} from "path/to/main.js";
thats it, few lines of code, no hacky, all vuejs power.
The docs address this situation
https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
If your components have the same parent, you can emit an event that the parent listens to. Then with the ref property set, you can call the c1method from the parent.
https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs
Try this out.
<template>
...
<component1 ref='componentOne'>
...
</template>
<script>
Vue.component('component2', {
methods: {
c2method: function(){
this.$refs.componentOne.c1method();
}
}
});
</script>
If anyone is looking for a solution in Vue.js v3:
https://v3-migration.vuejs.org/breaking-changes/events-api.html#event-bus
https://github.com/developit/mitt#install
import mitt from 'mitt'
const emitter = mitt()
// listen to an event
emitter.on('foo', e => console.log('foo', e) )
// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )
// fire an event
emitter.emit('foo', { a: 'b' })
// clearing all events
emitter.all.clear()
How do I fetch data once a component has been mounted? I start my vue instance and then load in the component, the component template loads in fine but the function calls in mounted are never run so the stats object remains empty, in turn, causing errors in the component/template that requires the data.
So how do I run a certain function on component load?
For what its worth... the functions I want to call will all make REST requests but each component will be running different requests.
Vue.component('homepage', require('./components/Homepage.vue'), {
props: ["stats"],
mounted: function() {
this.fetchEvents();
console.log('afterwards');
},
data: {
loading: true,
stats: {}
},
methods: {
fetchEvents: function() {
this.$http.get('home/data').then(function(response) {
this.stats = response.body;
this.loading = false;
}, function(error) {
console.log(error);
});
}
}
});
const vue = new Vue({
el: '#main',
mounted: function() {
console.log('main mounted');
}
});
You are already doing it fine by putting all the initialization stuff into mounted. The reason your component is not refreshing is probably because of binding of this, as explained below:
In your fetchEvents function, your $http success handler provides a response, which you are attempting to assign to this.stats. But it fails because this points to that anonymous function scope and not to Vue component.
To overcome this issue, you may use arrow functions as shown below:
fetchEvents: function() {
this.$http.get('home/data').then(response => {
this.stats = response.body;
this.loading = false;
}, error => {
console.log(error);
});
}
Arrow functions do not create its own scope or this inside. If you use this inside the arrow function as shown above, it still points to Vue component, and therefore your component will have its data updated.
Note: Even the error handler needs to use arrow function, so that you may use this (of Vue component) for any error logging.