ChatGPT解决这个技术问题 Extra ChatGPT

How to call a vue.js function on page load

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


t
tony19

You can call this function in 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.


@PhillisPeters can you put more code, or create a fiddle of it.
@PhillisPeters Please have a look at updated fiddle, I have replaced http post call with setTimeout for simulation, now you can see data being populated in table.
@GeorgeAbitbol Please feel free to update the answer accordingly.
My issue was that I did not know to use "this" in the mounted() section, and I was getting function undefined errors. "This" is used above, and I picked up that this was the solution to my issue, but it is not highlighted in the answer. Was the OP's issue similar to mine? Would adding a call-out to address binding issues make this answer better?
T
The Alpha

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()
    }
});

Try created instead.
@PhillisPeters You can use created or beforeMount.
t
tony19

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)
}
....

t
tony19

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
  })
}

4
4b0

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>

Z
Zach Jensz
methods: {
  methodName() {
    fetch("url").then(async(response) => {
      if (response.status === 200) {
        const data = await response.json();
        this.xy = data.data;
        console.log("Success load");
      }
    })
  }
}

Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.