Skip to content

Instantly share code, notes, and snippets.

@woile
Last active May 17, 2021 14:21
Show Gist options
  • Select an option

  • Save woile/cdc136ebab1d3aa3355c506f0c6e6d19 to your computer and use it in GitHub Desktop.

Select an option

Save woile/cdc136ebab1d3aa3355c506f0c6e6d19 to your computer and use it in GitHub Desktop.
vue

Vue

There is always a base app I guess. We are gonna use the following base app for the coming examples.

var app = new Vue({
  el: "#app",
  data: {
    message: "You loaded this page on " + new Date().toLocaleString(),
    seen: true,
    todos: [
      { text: "Learn JavaScript" },
      { text: "Learn Vue" },
      { text: "Build something awesome" },
    ],
    active: true,
  },
  methods: {
    // activate actives a swatch (emoji/color)
    activate: function (swatch) {
      this.active = swatch;
    },
  },
});

Syntax

Attribute Description Example
v-html insert raw HTML. Do not use with user provided content
v-bind:* Use property from the data property in App. Shortcut: :. Same as react props <span v-bind:title="message"></span> or <span :title="message"></span>
v-if Conditionals <span v-if="seen">Now you see me</span>
v-for Conditionals <li v-for="todo in todos">{{ todo.text }}</li>
v-model Used to read from input forms <p>{{ message }}</p><input v-model="message">
v-on Used to bind events. Shortcut: @ <a @click="doSomething"> ... </a>

Components

Essentially a Vue instance with pre-defined options.

Registering component

Vue.component("todo-item", {
  props: ["todo"],
  template: "<li>{{ todo.text }}</li>",
});
var app = new Vue(...)  // here we would use the same as above

This is registering the component globally. If you want them locally, just use components as part of any component.

import ComponentA from "./ComponentA.vue";

Vue.component("todo-item", {
  props: ["todo"],
  template: "<li>{{ todo.text }}</li>",
  components: {
    "display-date": DisplayDate,
  },
});

If you notice, we are using template instead of el. Vue tries to read from el first, and then from template.

Usage

Then, we can use inside another component the created component.

<ol>
  <!-- Create an instance of the todo-item component -->
  <todo-item
    v-for="item in groceryList"
    v-bind:todo="item"
    v-bind:key="item.id"
  ></todo-item>
</ol>

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment