I use vue-router and jQuery in the template,when i switch router $(document).ready() is failure

后端 未结 2 1053
感情败类
感情败类 2021-01-24 06:36

I do not know jQuery in vue correct usage. When I refresh page, $(document).ready() has a role. But when I switch the page through vue-router, $(document).rea

相关标签:
2条回答
  • 2021-01-24 06:52

    Instead of relying on $(document).ready() in a vue webapp, you can use one of the lifecycle hooks for this purpose. You can try using mounted as it comes pretty close to $(document).ready():

    Called after the instance has just been mounted where el is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called.

    You can hook it like this:

    <script>
        export default {
            name: 'photo',
            data() {
                return {
                    photos: [
                        {},{},{},{},{}
                    ]
                }
            },
            mounted () {
              console.log('something')
            }
        }
    
    0 讨论(0)
  • 2021-01-24 07:12

    I know that you've probably got the answer you were looking for, but for those who came here to find a way to use jQuery inside vue:

    you should just add a script tag on your index.html file and after that you can use $ variable whenever the component is created by vue. just like one of life cycle hooks that Saurabh mentioned, or as a method invoked by a v-on directive.

    e.g.:

    <template>
        ///get user name and password here through inputs///
        <button v-on:click="submit"> submit me please</button>
    </template>
    
    <script>
    export default {
        name: 'something',
        data() {
            return {
                username : '',
                password : '',
                baseUrl : 'felan.com'
            }
        },
        methods: {
            submit() {
    
                $.post(this.baseUrl + '/member/login', {
                    username: this.username,
                    password: this.password,
                }).then((response) => {
                    if (response.valid) {
                        //do something
                    } else {
                        //do something else
                    }
                }).fail(() => console.log('failed'))
            }
        }
    }
    </script>
    
    <style>
    </style>
    
    0 讨论(0)
提交回复
热议问题