[Vuejs]-Declare a vue template in javascript

0👍

Here is an example utilizing the render function instead of the typical single-page component:

var SomeElement = {
  render: function (createElement) {
    return createElement(
      "h1",
      this.name
    )
  },
  props: {
    name: {
      type: String,
      required: true
    }
  }
};

new Vue({
  el: "#app",
  components: { SomeElement: SomeElement },
  template: "#app-template",
  data: function() {
    return {
      num: 0
    }
  },
  methods: {
    increaseNames: function() {
      this.num += 1;
    },
    decreaseNames: function() {
      if (this.num === 0) return;
      this.num -= 1;
    }
  }
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Example</title>
</head>
<body>
  <div id="app"></div>
  <script type="text/x-template" id="app-template">
    <div>
      <some-element v-for="n in num" :name="'Derek-' + n" :key="n" />
      <button @click="increaseNames">Add another name</button>
      <button @click="decreaseNames">Remove another name</button>
    </div>
  </script>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</body>
</html>

As you can see, SomeElement is essentially a pure javascript object that is included in the App component.

EDIT

I included a way to dynamically add elements to the vue template with the built-in vue methods attribute. Keep in mind that the idea behind using a framework like vue is to pre-define your components and then utilize them as much or as little as possible – even dynamically, as is shown in this particular instance.

Leave a comment