Vue.js 2.0 Basics

By Dev Coffee

Create Vue.js object - This creates new Vue object that targets the id of the div tag. You can then data bind the keyword property.

const app = newVue({
    el: '#app',
    data: {
        keyword: 'Javascript'
    }
});

<div id='app'>
    {{keyword}}
</div>

Loop through a list - use the v-for attribute to loop through a list in your data object.

class RedditPost {
  constructor(title, link) {
    this.title = title;
    this.link = link;
  }
}

const app = newVue({
    el: '#app',
    data: {
        keyword: 'Javascript,
        posts: [
          new RedditPost('Vue.js', 'link1'),
          new RedditPost('React.js', 'link2'),
          new RedditPost('Express.js', 'link3'),
        ]
    }
});


<div v-for="post in posts">{{post.title}} - {{post.link}}</div>

Display data based on conditions - Use 'v-if, v-else-if, and v-else' to dynamically change your Vue content.

<h1 v-if="isVisible == 'if'">If</h1>
<h1 v-else-if="isVisible === 'elseif'">Else If</h1>
<h1 v-else>Else</h1>

data: { isVisible: 'if' }

Access Vue object through browser console - You are able to change data inside the browser console by accessing your Vue object like the following. (This will reflect in the view)

app.isVisible = !app.isVisible;

Styles and classes - You can add / remove styles and classes based on conditions

const app = new Vue({
    el: '#app',
    data: {
        toggleStyle: true,
        toggleClass: true
    }    
}); 

<!-- css -->
.red {
  background: red;
}

.blue {
  background: blue;
}

.box {
  width: 100px;
  height: 100px;
  border: 1px solid rgba(0,0,0,.12);
}
<!-- css -->

<div id="app">
  {{toggleStyle}}
  {{toggleClass}}
  <div class="box" v-bind:class="{blue: toggleStyle}"></div> // You can do any conditional (2 > 3) for example
  <div class="box" v-bind:style="{blue: toggleStyle}"></div>
</div>

Ternary with v-bind:class

<div class="box" v-bind:class="[toggleStyle ? 'blue' : 'red']"></div>

Binding to inline styles with v-bind:style

// JS
const app = new Vue({
    el: '#app',
    data: {
        styleObj: {
            color: 'red',
            fontSize: '128px'
        }
    }
});

results matching ""

    No results matching ""