简体   繁体   中英

How can I add Vue or React to an existing Wordpress site?

I'm wondering what's the best way about adding a front end, componentized framework to a Wordpress site without using the Rest API.

I'm taking over two sites built with the Woocommerce Storefront theme, and I'd like to add a reliable front end library. Would it be best to just build my own as I need it? I'd like to avoid jQuery as I find it gets messy pretty quickly.

Would a good course of action be to build a plugin which generates a Post type with the framework added in, or is there a way I can add my framework to the whole site and implement it incrementally.

If you start a new project from scratch, I would recommend using Sage: https://roots.io/sage/ .

One big deal when it comes to use React / Vue.js for any kind of projects is you need to setup the build (using Webpack for example), to compile them and get the best of out these frameworks. Sage takes care of these tasks for you and have webpack and browserify integrated so you have hot loading for dev and proper build for production. That's really an advantage.

With your case, because your sites have been built using Storefront, so integrate fully with Sage seems to be not an option, however, you can still borrow some ideas from Sage.

Sage set it scripts up in the way that your script can be separated into routes , though these routes are not exactly the same as ones of a single page app. Basically, they have an util function called Router , which will execute JS functions based on the classes inserted into the body element. I find it works extremely well with Vue.js and React. For instances: in your homepage, you want to place couple of Vue components inside a <div id="homepage"> element, you can define it as follows:

export default {
  init() {
    new Vue({
      el: '#homepage',
      name: 'HomePageApp',
      components: {
        ...
      },
    });
  },
  finalize() {
    // JavaScript to be fired on the home page, after the init JS
  },
};

Then import and add it to your Router :

const routes = new Router({
  ...
  // Home page
  homepage,
});

I recommend having a look at how Sage does that in your Github repo, it's pretty straight forward and guarantee a well-organised, well-structured front-end: https://github.com/roots/sage/blob/master/resources/assets/scripts/main.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM