9

I found detailed instructions here on how to create a Stack Snippet for React, but I have been unable to figure out how to do so for a Vue.js component.

How do I create a runnable Stack Snippet of a Vue.js component?

1
  • It's not super locatable, but a tutorial for converting a Vue component into a Snippet exists at the very end of the vue.js tag wiki.
    – zcoop98
    Apr 6, 2022 at 15:15

3 Answers 3

12

Below is a (slightly updated) direct copy from something I initially wrote into the end of the tag wiki; I figure it's a good starting point for creating a more comprehensive resource.

I'm currently unfamiliar with Vue 3, so I'm unsure about whether or how much this guidance needs to be updated to be compatible.

All are encouraged to edit this in any way to improve its usefulness as a resource!


Converting a Vue Component into a Stack Snippet

It is often useful to share runnable snippets of code in questions regarding Vue components. Since Stack Snippets can't natively run Vue single file components (.vue files), it's necessary to do a little conversion work.

To create a Stack Snippet containing Vue in a Stack Overflow post, make sure you:

  1. Import Vue into the HTML section of the snippet
    • You can do this through the sidebar menu of the snippet editor itself, if it includes your desired version:
      Vue version select in snippet editor sidebar
    • Or by manually adding a <script> tag referencing the version you need:
      (eg. <script src="https://unpkg.com/vue@2"></script>)
    • NOTE: It's important that the Vue import is before other imports of libraries that depend on Vue (eg. Vue Router)
  2. Wrap component JavaScript with new Vue({...})
    • Replace default export with new Vue, and don't forget the parenthesis () around your brackets {}
    • Note that you won't be able to use import statements, so you should trim everything out of the snippet that's not strictly necessary to understand your question and the problem at hand
    • You may also need to add example data if your component relied on props or APIs
  3. Tell the new Vue instance where to render in your HTML
    • Use the el property of the new Vue instance to indicate what HTML container Vue should render in (see example below)

You may also want to replace your <template> HTML elements with some alternative (ie. <div>) if it causes issues.

Starting with something like this:

HelloWorld.vue

<template>
  <div>
    <p>{{ message }}</p>
    <input v-model="message">
  </div>
</template>

<script>
  export default {
    data() {
      return {
        message: 'Hello World!'
      }
    }
  }
</script>

Will end up with something like this:

HelloWorld.html

<html>
<div id="app">
  <p>{{ message }}</p>
  <input v-model="message">
</div>

<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
  new Vue({
    el: '#app', //Tells Vue to render in HTML element with id "app"
    data() {
      return {
        message: 'Hello World!'
      }
    }
  });
</script>
</html>

You can drop this straight into the HTML section of a snippet, or split it into the HTML and JavaScript sections accordingly. Bear in mind that splitting it may make the code clearer to readers!

<html>
<div id="app">
  <p>{{ message }}</p>
  <input v-model="message">
</div>

<!-- Don't forget to include Vue from CDN! -->
<script src="https://unpkg.com/vue@2"></script>
<script>
  new Vue({
    el: '#app', //Tells Vue to render in HTML element with id "app"
    data() {
      return {
        message: 'Hello World!'
      }
    }
  });
</script>
</html>

8

Here's a Vue 3 snippet.

const App = {
  name: "App",
  data() {
    return {
      message: "hello world",
    };
  },
};

Vue.createApp(App).mount('#app');
<div id="app">
  <p>{{message}}</p>
  <input v-model="message">
</div>

<script src="https://unpkg.com/vue@3"></script>

Here's a larger example with multiple components and assorted functionality:

"use strict";

const Test = {
  name: "Test",
  template: document.querySelector("#test").innerHTML,
  props: ["labelName"],
  data() {
    return {
      name: "",
      names: [],
    };
  },
  methods: {
    onReset() {
      this.name = "";
    },
    submit() {
      this.names.push(this.name);
      this.name = "";
    },
  },
};

const App = {
  name: "App",
  template: document.querySelector("#app-template").innerHTML,
  data() {
    return {
      message: "hello world",
      user: null,
    };
  },
  components: {
    Test,
  },
  mounted() {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
        this.user = json;
      });
  },
  computed: {
    reversedMessage() {
      return [...this.message].reverse().join("");
    },
  },
};

Vue.createApp(App).mount('#app');
<template id="app-template">
  <p>{{reversedMessage}}</p>
  <input v-model="message">
  <pre v-if="this.user">{{JSON.stringify(user, null, 2)}}</pre>
  <pre v-else>loading...</pre>
  <test label-name="test label"></test>
</template>

<template id="test">
  <form @submit.prevent="submit" @reset="onReset">
    <div>
      <label>{{labelName}}
        <input v-model="name" />
      </label>
    </div>
    <button type="submit">submit</button>
    <button type="reset">reset</button>
  </form>
  <div>
    <ul>
      <li v-for="n of names">{{n}}</li>
    </ul>
  </div>
</template>

<div id="app"></div>
<script src="https://unpkg.com/vue@3"></script>

If you want to disable the production tip, see How do I turn off the productionTip warning in Vue 3?, or add the CSS .as-console-wrapper{display:none!important}, assuming you don't mind hiding errors and all other logs.

To be a bit more precise than the CSS solution at the expense of uglier code, you can add the following JS to prune out only the production tip row from the console:

setTimeout(() => [...document.querySelectorAll(".as-console-row")]
  .forEach(e => e.textContent.includes("build of Vue") && e.remove()
), 0);
4
  • is it possible to include a three.js snippet like this one inside the Vue snippet? thanks in advance.
    – Bilal
    Dec 13, 2022 at 14:17
  • Yes, I'm sure it's possible.
    – ggorlen
    Dec 13, 2022 at 17:28
  • is there an example that you are aware of?
    – Bilal
    Dec 13, 2022 at 17:43
  • None that I'm aware of offhand.
    – ggorlen
    Dec 13, 2022 at 18:00
4

It can be done with an object-formatted component (with <template> tags, as opposed to a single file component).

Select a recent version of vue from the "Options" on the left pane, then...

Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    message: 'World'
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <h1>Hello {{ message }}</h1>
</div>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .