【问题标题】:I use vue-router and jQuery in the template,when i switch router $(document).ready() is failure我在模板中使用 vue-router 和 jQuery,当我切换路由器 $(document).ready() 失败
【发布时间】:2023-04-01 13:42:01
【问题描述】:

我不知道 jQuery 在 vue 中的正确用法。当我刷新页面时,$(document).ready() 有作用。但是当我通过vue-router切换页面时,$(document).ready()不起作用。

<template>
    <div id="photo_wrap">
        <div class="photo_frame" v-for="(photo,index) in photos">
            <img v-bind:src=" 'src/assets/photo/' + index + '.jpg' ">
        </div>
    </div>
</template>

<script>
    import $ from 'jquery'
    export default {
        name: 'photo',
        data() {
            return {
                photos: [
                    {},{},{},{},{}
                ]
            }
        }
    }

    $(function () {
        console.log('something')
    })

</script>

【问题讨论】:

  • 右键,查看新路由的源码。包含 jQuery 吗?不是?确保包含在内。

标签: javascript jquery vue.js vuejs2 vue-router


【解决方案1】:

您可以使用 lifecycle hooks 之一来实现此目的,而不是在 vue webapp 中依赖 $(document).ready()。您可以尝试使用mounted,因为它非常接近$(document).ready()

在实例刚刚挂载后调用,其中 el 被新创建的 vm.$el 替换。如果根实例挂载到文档内元素,则调用 mount 时 vm.$el 也将在文档内。

你可以这样挂起来:

<script>
    export default {
        name: 'photo',
        data() {
            return {
                photos: [
                    {},{},{},{},{}
                ]
            }
        },
        mounted () {
          console.log('something')
        }
    }

【讨论】:

    【解决方案2】:

    我知道你可能已经得到了你想要的答案,但是对于那些来这里寻找在 vue 中使用 jQuery 的方法的人:

    你应该在你的 index.html 文件中添加一个脚本标签,然后你可以在 vue 创建组件时使用 $ 变量。就像Saurabh 提到的生命周期钩子之一,或者作为由 v-on 指令调用的方法。

    例如:

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

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 2010-10-02
      • 1970-01-01
      • 2019-05-28
      • 2011-09-21
      • 2019-12-28
      • 2021-03-09
      • 2021-11-06
      • 2020-10-14
      相关资源
      最近更新 更多