Nuxt中如何使用owl轮播?

How to use owl carousel in Nuxt?

我想让脚本在每个页面上运行,而不需要加载这些页面; 我的静态文件夹中有 owl caroussel 脚本,我已经将它放在 nuxt.config.js 中,这里是我的放置方式:

head: {
    title: 'title',
    htmlAttrs: {
        lang: 'en'
    },
    meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' },
        { hid: 'description', name: 'description', content: '' },
        { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
        { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
    script: [{
            src: process.env.BASE_URL_ROOT + "/jquery-3.3.1.min.js",
            type: "text/javascript"
        },
        {
            src: process.env.BASE_URL_ROOT + "/owl.carousel.min.js",
            type: "text/javascript"
        },
        {
            src: process.env.BASE_URL_ROOT + "/main-script.js",
            type: "text/javascript"
        }
    ]
},

还有我的主脚本-script.js:

$(document).ready(function() {

$('.owl-menu').owlCarousel({
    loop: true,
    responsiveClass: true,
    center: true,
    items: 6,
    nav: true,
    dots: false,
    autoWidth: true,
    responsive: {
        600: {
            items: 6,
            nav: true,
            autoWidth: true,
            center: true,
            loop: true
        },
    }
})

$('.owl-video').owlCarousel({
    loop: true,
    center: true,
    items: 3,
    margin: 10,
    nav: true,
    dots: true,
    responsive: {
        600: {
            items: 3,
            margin: 12,
        },
    },
    navContainer: "#nav-conte",
    navText: [
        '<i class="far fa-arrow-alt-circle-left" aria-hidden="true" style="color: rgba(0,0,0,0.67843);"></i>',
        '<i class="far fa-arrow-alt-circle-right" aria-hidden="true" style="color: rgba(0,0,0,0.67843);"></i>'
    ]
})
})

如果页面已加载,轮播在页面上运行良好,但如果它来自 nuxt 导航,轮播脚本将不再工作。


我使用的解决方案是 MutationObserver,它查看 DOM 上的变化;在我的 main-script.js:

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var observer = new MutationObserver(function(mutations, observer) {
    // my owl caroussel script
});

observer.observe(document, {
    subtree: true,
    attributes: true
});

在这里,您使用的一些 jQuery 代码依赖于选择 DOM 的特定部分。同时,如今的前端框架确实以不同的方式处理 DOM,并且比实际的 querySelector.

更依赖于状态或 refs

因此,我什至不建议尝试连接它。您可能应该尝试使用 Vue 包来制作相同类型的功能。
它可能不那么重(包大小),更容易与您的 Nuxt 应用程序集成,并且您不会依赖于错误和 hacky 行为。

查看此轮播列表:https://github.com/vuejs/awesome-vue#carousel

我确实使用 vue-awesome-swiper,更重一些但确实完整。


另外,我不知道你是否真的需要在 Vue 之上的 Nuxt 应用程序中安装 jQuery,但是如果你想要一种干净简单的方法将它安装到你的 Nuxt 应用程序中,你在这里关注我的其他答案:


编辑,甚至 owl carousel deprecates itself 如您所见