Cover

Remote Views in Vue.js

March 11, 2018
No Comments.

I’ve been digging into Vue.js a lot lately. I’m working on a new course on it that will be released on May 1st.

Coming from Angular and Angular.js, I was surprised to see that remote views were not supported out of the box. Now I’m not using it with Webpack or Browserfy, so I am probably using it outside the norm. But I still think remote views (or in the case of hosting in ASP.NET, generated views) are a powerful idea.

I kept looking for a plugin that would support it. I was ready to ditch the whole idea when I saw in the docs they explained in there (almost).

So let me walk you through it. I haven’t tried this with a simple Vue.js instance, but only with a component since that’s probably the best way to do it anyway. So as a reminder, to create a component, you need to either embed a component, or just create a global component like so:

Vue.component("remote-vue", {
  template: "<div>Hello World</div>"
});

But then I noticed that they also support async components:

Vue.component("remote-vue", function (resolve, reject) {
  resolve({
    template: "<div>Hello World</div>"
  });
  }
});

Again, Vue doesn’t support a native network stack, so whether you’re using jQuery or something like axios, it’s just up to you to make the call to get the template:

Vue.component("remote-vue", function (resolve, reject) {
  // using axios for the network call
  axios.get("/templates/remote-vue.html")
    .then(function (response) {
      resolve({
        template: response.data
      });
    })
    .catch(function () { reject(); });
  }
});

The magic here is that you’re passing in a promise so that you can resolve with the found data or reject it in the case of an error.

My real example uses more than just a template:

(function () {

  // Create Components
  Vue.component("remote-vue", function (resolve, reject) {
    axios.get("/templates/remote-vue.html")
      .then(function (response) {
        resolve(createRemoteVue(response.data));
      })
      .catch(function () {
        console.log("FAILED");
        reject();
      });
  });

  function createRemoteVue(template) {
    return {
      template: template,
      data: function () {
        return {
          foo: "Hello",
          items: [{
              name: "Shawn",
              age: 48
            },
            {
              name: "Steve",
              age: 33
            }
          ]
        };
      },
      methods: {
        onSave: function (item) {
          alert(item.name); 
        }
      }
    }
  }


  // Bootstraping the vue
  var vm = new Vue({
    el: "#theApp"
  });
})();

You can find that in this repo if you want to play with it (just npm start to get it started):

https://github.com/shawnwildermuth/RemoteVueExample

Let me know if you think you’d use Vue.js this way!