How to Build a Reusable Vue Comment Component for Legacy jQuery Pages with Vue‑CLI 3

This guide explains how to create a Vue‑based comment system, mount it inside a traditional jQuery page, package it as a UMD library with Vue‑CLI 3.0, manage state with Vuex, integrate Element‑UI components, and extend Axios for JSONP support.

AutoHome Frontend
AutoHome Frontend
AutoHome Frontend
How to Build a Reusable Vue Comment Component for Legacy jQuery Pages with Vue‑CLI 3

Background

The article demonstrates how to refactor a jQuery‑based comment system into a reusable Vue component and package it as a UMD library that can be loaded in both legacy jQuery pages and modern Vue applications.

Problem Analysis

How to run a Vue component inside a jQuery page.

How the component communicates with other page features.

Whether using a Vue component increases payload size and how to mitigate it.

Mounting Vue in a jQuery Page

Provide a mounting point and load the required scripts:

<div id="app"></div>
<script src="https://cdn.bootcss.com/vue/2.5.15/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>
<script src="./commentSystem.umd.min.js"></script>
<script>
  new Vue({ render: h => h(window["commentSystem"]) }).$mount('#app');
</script>

Building the Component with Vue‑CLI 3.0

Use the library target to generate a UMD bundle:

vue-cli-service build --target lib --name myLib [entry]

The build produces files such as dist/myLib.umd.min.js (13.28 KB gzipped) and other formats.

Component Internal Communication with Vuex

Define a Vuex store inside CommentSystem.vue and attach it to the component:

import Vue from 'vue';
import Vuex, { mapState } from 'vuex';
Vue.use(Vuex);
export default {
  name: 'CommentSystemComponent',
  store: store
};

The store is imported directly in the component because the component itself is the library entry point.

Communication Between Component and Page

From the page, obtain the component instance and commit Vuex mutations:

var rootComponent = new Vue({
  render: h => h(window["comment-system"])
}).$mount('#app');
ahCSConfig.$comment = rootComponent.$children[0].$children[0];

document.querySelector('#btn').addEventListener('click', function () {
  ahCSConfig.$comment.$store.commit('SET_PICTURE_DIALOG_DATA', {
    visible: true,
    info: 'http://www3.autoimg.cn/...jpg'
  });
}, false);

The component can also expose an event callback that the page registers. Every store.commit triggers this callback:

const ahCSConfig = window.ahCSConfig;
const eventInterceptors = store => {
  store.subscribe((mutation, state) => {
    ahCSConfig && ahCSConfig.event && ahCSConfig.event(mutation);
  });
};
export default new Vuex.Store({ plugins: [eventInterceptors] });

Using External UI Library (Element‑UI)

Install babel-plugin-component to enable on‑demand imports and configure .babelrc:

{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    ["component", {
      "libraryName": "element-ui",
      "styleLibraryName": "theme-chalk"
    }]
  ]
}

Import only the needed components and register them globally:

import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);

new Vue({
  el: '#app',
  render: h => h(App)
});

Extending Axios to Support JSONP

A helper reqMethod decides whether to perform a JSONP request or a normal Axios request based on the method argument:

/**
 * Request wrapper supporting JSONP and standard HTTP methods.
 * @param {string} method   Request method ('get', 'post', 'jsonp', etc.)
 * @param {string} url      Request URL
 * @param {object} obj      Parameters or payload
 * @param {object} config   Optional Axios config
 * @return {Promise}
 */
function reqMethod(method, url, obj, config = {}) {
  if (method.toLocaleLowerCase() === 'jsonp') {
    let q = Object.assign({}, obj, { '_': new Date().getTime() });
    return new Promise((resolve, reject) => {
      let path = url + '?' + qs.stringify(q);
      jsonp(path, { timeout: axios.defaults.timeout }, function (err, data) {
        if (err) { MsgToast('err'); return reject(err); }
        MsgToast({ data, requestURL: path });
        if (data.returncode !== undefined && data.returncode !== 0) {
          console.warn('JSONP response interceptor caught abnormal code:', data);
          return Promise.reject(new Error('状态码异常'));
        }
        resolve(data);
      });
    });
  }

  let modeKey = ['post', 'put'].includes(method.toLowerCase()) ? 'data' : 'params';
  return new Promise((resolve, reject) => {
    axios({
      method: method.toLowerCase(),
      url: url,
      [modeKey]: obj || {},
      ...config
    }).then(response => resolve(response.data, url))
      .catch(error => reject(error));
  });
}

Conclusion

Vue‑CLI 3.0 enables easy output of a component as a UMD library, allowing seamless integration into both traditional jQuery environments and modern Vue applications. The approach leverages Vuex for internal state management, Element‑UI for UI elements, and a custom Axios wrapper for JSONP support.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ComponentVueaxiosVuexElement-UIjQueryUMD
AutoHome Frontend
Written by

AutoHome Frontend

AutoHome Frontend Team

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.