Sử dụng hiệu ứng hạt Particles trong Vue 3

Cài đặt

Thực hiện cài đặt thư viện particles.vue3 trong dự án Vue 3:


// Cài đặt qua npm
npm install particles.vue3 --save

// Cài đặt qua yarn
yarn add particles.vue3 --save

// Đối với dự án dùng TypeScript, cần cài đặt thêm
npm i tsparticles

Cấu hình trong dự án Vue 3 + TypeScript

Tạo file khai báo module

Tạo file env.d.ts trong thư mục src để khai báo module:


declare module 'particles.vue3';

Kích hoạt Particles trong main.ts


import { createApp } from 'vue'
import App from './App.vue'
import Particles from 'particles.vue3'

createApp(App).use(Particles).mount('#app')

Sử dụng component Particles trong giao diện


<template>
  <div>
    <Particles
      id="tsparticles"
      :particlesInit="initializeParticles"
      :particlesLoaded="handleParticlesLoaded"
      :options="particleOptions"
    />
  </div>
</template>

Phần logic xử lý trong script:


<script setup lang="ts">
import { reactive } from 'vue'
import { loadFull } from "tsparticles"
import type { Engine } from 'tsparticles-engine'

const initializeParticles = async (engine: Engine) => {
    await loadFull(engine)
}

const handleParticlesLoaded = async (container: any) => {
    console.log('Particles container loaded', container)
}

const particleOptions = reactive({
    background: {
        color: { value: '#000' }
    },
    fpsLimit: 60,
    interactivity: {
        events: {
            onClick: {
                enable: true,
                mode: 'push'
            },
            onHover: {
                enable: true,
                mode: 'grab'
            },
            resize: true
        },
        modes: {
            bubble: {
                distance: 400,
                duration: 2,
                opacity: 0.8,
                size: 40
            },
            push: { quantity: 4 },
            repulse: {
                distance: 200,
                duration: 0.4
            }
        }
    },
    particles: {
        color: { value: '#ffffff' },
        links: {
            color: '#ffffff',
            distance: 150,
            enable: true,
            opacity: 0.5,
            width: 1
        },
        collisions: { enable: false },
        move: {
            direction: 'none',
            enable: true,
            outMode: 'bounce',
            random: false,
            speed: 4,
            straight: false
        },
        number: {
            density: { enable: true, area: 800 },
            value: 80
        },
        opacity: { value: 0.5 },
        shape: { type: 'circle' },
        size: { random: true, value: 5 }
    },
    detectRetina: true
})
</script>

Thẻ: vue-3 typescript particles.js

Đăng vào ngày 4 tháng 6 lúc 20:39