Vue组件集成依赖jQuery的Pollfish WebSDK,点击按钮无响应问题排查
Let's break down the issues in your code and fix them one by one:
1. Missing Pollfish Initialization
The biggest issue is that you've defined your pollFishConfig but never called Pollfish.init(pollFishConfig) to initialize the SDK. The working example you referenced explicitly uses this method, which is mandatory to set up Pollfish with your configuration.
2. Misusing Computed Properties for Side Effects
Your addJQuery and addPollFishSDK are set as computed properties, but they're performing DOM manipulations (adding script tags) which are side effects. Computed properties should be pure functions that return values, not execute state changes or DOM actions. We'll convert these to methods with promise-based loading instead.
3. Callback Order & Scope Issues
You referenced callback functions (like onSurveyAvailable) in your config before defining them. While JavaScript function hoisting might avoid errors, it's cleaner to define callbacks first, and we'll make sure they update your component's data to reflect survey state.
4. Asynchronous Script Loading
jQuery and Pollfish SDK load asynchronously, so we need to ensure Pollfish is initialized only after both scripts are fully loaded to avoid race conditions.
Corrected Component Code
<template> <div class="container" v-if="isFreePlan"> <h2>Remove ads and save unlimited projects for 5 days</h2> <button @click="showFullSurvey" :disabled="!pollfishInitialized">Take {{ lengthOfInteraction }} Survey Now</button> </div> </template> <script> import { mapGetters } from 'vuex'; export default { data() { return { surveyAvailable: false, lengthOfInteraction: '', pollfishInitialized: false }; }, methods: { showFullSurvey() { if (this.pollfishInitialized && typeof Pollfish !== 'undefined') { Pollfish.showFullSurvey(); console.log('Attempting to show survey'); } else { console.log('Pollfish not ready yet'); } }, // Load jQuery and return a promise for async handling loadJQuery() { return new Promise((resolve, reject) => { const url = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js'; if (document.querySelector(`script[src='${url}']`)) { resolve(window.jQuery); return; } const jqueryScript = document.createElement('script'); jqueryScript.src = url; jqueryScript.onload = () => resolve(window.jQuery); jqueryScript.onerror = () => reject(new Error('Failed to load jQuery')); document.body.appendChild(jqueryScript); console.log('jQuery script added'); }); }, // Load Pollfish SDK and return a promise loadPollfishSDK() { return new Promise((resolve, reject) => { const url = 'https://storage.googleapis.com/pollfish_production/sdk/webplugin/pollfish.min.js'; if (document.querySelector(`script[src='${url}']`)) { resolve(window.Pollfish); return; } const pollfishScript = document.createElement('script'); pollfishScript.src = url; pollfishScript.onload = () => resolve(window.Pollfish); pollfishScript.onerror = () => reject(new Error('Failed to load Pollfish SDK')); document.body.appendChild(pollfishScript); console.log('Pollfish SDK script added'); }); }, // Initialize Pollfish once all dependencies are ready async initPollfish() { try { // Wait for both scripts to load await this.loadJQuery(); await this.loadPollfishSDK(); // Define callbacks first for clarity const onSurveyAvailable = (data) => { console.log('Survey Available', data); this.surveyAvailable = true; this.lengthOfInteraction = data.lengthOfInteraction; // Update UI with survey length }; const onSurveyNotAvailable = () => { console.log('Survey Not Available'); this.surveyAvailable = false; }; const onSurveyCompleted = () => { console.log('Survey Completed'); // Add logic here (e.g., update user plan via Vuex) }; const onUserDisqualified = () => { console.log('User Disqualified'); }; // Initialize Pollfish with your configuration const pollFishConfig = { api_key: "api-key", // Replace with your actual API key debug: process.env.NODE_ENV !== 'production', ready: () => { console.log('Pollfish is ready'); this.pollfishInitialized = true; }, uuid: this.userId, surveyAvailable: onSurveyAvailable, surveyNotAvailable: onSurveyNotAvailable, surveyCompletedCallback: onSurveyCompleted, userNotEligibleCallback: onUserDisqualified }; Pollfish.init(pollFishConfig); } catch (error) { console.error('Error initializing Pollfish:', error); } } }, computed: { ...mapGetters("session", ['userId']), ...mapGetters("account", ["isFreePlan"]) }, mounted() { // Start initialization when component mounts this.initPollfish(); } }; </script>
Key Improvements Explained
- Promise-based Loading: Ensures we wait for jQuery and Pollfish to fully load before initializing, eliminating race conditions.
- Explicit Initialization: Added
Pollfish.init(pollFishConfig)which was missing in your original code—this is the critical step to activate the SDK. - UI State Updates: Callbacks now update component data, so your template can react to survey availability and details.
- Safety Checks: The button is disabled until Pollfish is initialized, preventing premature clicks.
- Error Handling: Try/catch blocks catch and log issues with script loading or SDK initialization.
内容的提问来源于stack exchange,提问作者Constantinos N

