vue create myProjectOR
vue create .
npm run serve
vue ui
MyComponent
under components folderexport default { components: { MyComponent } }
<template> <div> <MyComponent /> </div> </template>
export default { props: { msg: String } }
<h1>{{ msg }}</h1>
<MyComponent msg="Welcome"/>
<template> <div> <div> <input type="text" @input="onTypingText" /> </div> <div> Output: <div>Reversed string: {{ reverse }}</div> <div>Changed: {{ textInput + 'abc' }}</div> <div>Changed: {{ textInput.split('').reverse().join('') }}</div> <div>Today is {{ new Date().getDay() === 3 ? 'Wednesday' : 'Other day' }} </div> </div> </div> </template> <script> export default { name: "myComponent", props: { msg: String, }, data() { // any time data property is updated, the component is instantly re-rendered return { // Initialize the state textInput: "", }; }, methods: { // Use these functions to change the data properties. It will cause to automatically re-render the template in the browser onTypingText(event) { this.textInput = event.target.value; }, }, // turn data into viewable values computed: { reverse() { return this.textInput.split('').reverse().join('') } } }; </script> <style scoped> input { width: 75%; } </style>
props: { image: { type: String, default: '/images/placeholder.png', validator: propValue => { ... return true } }, length: { type: [Number, String], --- possible data types default: 90, }, title: { type: String, required: true }, watched: { type: Boolean, default: false, } }Types:
String Number Boolean Array Object Date Function Symbols
Defines the 'initial state' of our Vue instance
Changes data
Defines the different ways our state can be changed
Used to display staff only when we need to run a 'computation' on data property before it shown.
Turns data into viewable staff
Defines how to turn the current data into viewable values
:
v-bind: src="image" :alt="description" :href="url" :title="toolTip" :class="isActive" :style="isStyled" :disabled="isDisabled"
v-show
OR
v-if
v-show
Toggle visibility
CSS property display: none
is added when not shown
<p v-show="inStock">In Stock</p>
v-if
Adding and removing from the DOM
<p v-if="isStock">In Stock</p> <p v-else>Out Of Stock</p>OR
<p v-if="inventory > 10">In Stock: {{ inventory }}</p> <p v-else-if="inventory <= 10 && inventory > 0">Almost Sold Out: {{ inventory }}</p> <p v-else>Out Of Stock</p>
v-for
<div v-for="item in variants" :key="item.id"> <p>{{ item.name }}</p> </div>
<ul> <li v-for="item in details" :key="item.id">{{ item }}</li> </ul>
<ul> <VideoItem v-for="current in videoList" :item="current" :key="current.id"></VideoItem> </ul>In the child component
<li> {{ item.name }} </li>
<div v-for="(item, index) in variants" :key="item.id" @mouseover="updateProduct(index)"> </div>
v-on:
OR @
cart: 0
<button v-on:click="cart += 1">Add to Cart</button>
methods: { addToCart: function () { this.cart += 1; },
<button v-on:click="addToCart">Add to Cart</button>
<p @mouseover="updateProduct(item.image)">{{item.variantColor}}</p>
<button @click="addToCart">Add to Cart</button> <div @mouseover="updateProduct">Color</div> <form @submit.prevent="addToCart">...</form> <input @keyup.enter="send"> <input @keyup="onTypingText"> <input @input="onTypingText">
methods: { addToCart: function () { this.cart += 1; }, updateProduct: function (varientImage) { this.image = varientImage; }, },
methods: { addToCart() { this.cart += 1; }, updateProduct(varientImage) { this.image = varientImage; }, },
<VideoList :videoList="videos"></VideoList>
data() { return { videos: [] } },
props: { videoList: { type: Array required: true } },OR
props: { videoList: Array },OR
props: ['videoList'],
onInput(event) { this.$emit('searchChange', event.target.value); }
<SearchBar @searchChange="onSearchChange"></SearchBar>
methods: { onSearchChange(value) { console.log(value); } }
main.js
export const eventBus = new Vue(); new Vue({ ... --- regular code })
import { eventBus } from '../main.js'; eventBus.$emit('ageWasChanged', this.age)
import { eventBus } from '../main.js';
created() { --- life cycle hook --- set a listener to listen to the event eventBus.$on('ageWasChanged', (age) => { console.log(age); }); }
main.js
export const eventBus = new Vue({ data: { }, methods: { changeAge(age) { this.$emit('agewasEdited', age); } } }); new Vue({ ... --- regular code })
import { eventBus } from '../main.js'; eventBus.changeAge(this.age);
import { eventBus } from '../main.js';
created() { --- life cycle hook --- set a listener to listen to the event eventBus.$on('ageWasChanged', (age) => { console.log(age); }); }
<div class="color-box" :style="{ background: currColor, fontSize: currSize }" ... > </div>
disabledButton
class if inStock
is
false.
<button v-on:click="addToCart" :disabled="!inStock" :class="{ disabledButton: !inStock }" > Add to Cart </button>
<div class="classObject"> ... </div>
<div class="arrayOfClasses"> ... </div>
<div :class="{ invalid: userNameValidity === 'invalid'}"> ... </div>
<div class="[isActive ? activeClass : '']"> ... </div>
<h1>{{ title }}</h1>
data: { brand: "Vie Mastery", product: "Socks", computed: { title() { return this.brand + ' ' + this.product; }, }, }
<img :src="image" alt="" /> OR <img v-bind:src="image" alt="" />
computed: { image() { return this.variants[this.selectedVariant].image; } },
<div id="nav"> <router-link :to="{ name: 'Home' }">Home</router-link> | <router-link :to="{ name: 'About' }">About</router-link> </div>
<div id="nav"> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> <a @click="logout">Logout</a> </div>
vue-router automatically applies two active classes,
.router-link-active and .router-link-exact-active, to the
<router-link></router-link>
component.
Original boilerplate has:
#nav a.router-link-exact-active { color: #42b983; }
<div id="nav"> <router-link to="/" active-class="active" exact>Home</router-link> | <router-link to="/about" active-class="active">About</router-link> </div>
{ path: "/about-us", name: "About", ... }, { path: "/about", redirect: { name: 'About'}, },
{ path: "/about-us", name: "About", alias: "/about", ... }
import router from "./router"; ... router.push('/'); router.push({ name: 'home' }); router.replace('/abc') --- we cannot go back (to check in Vue2)
const router = new VueRouter({ mode: "history", --- removes # in the url base: process.env.BASE_URL, routes, });
beforeCreate - Called immediately after instance is initialized, before options are processed. created - Called after the instance has been created. beforeMount - Right before mounting of the DOM begins mounted - Called when the instance has been mounted (browser updated). beforeUpdate - Called when reactive data has changed, before the DOM is re-rendered. updated - Called when reactive data has changed, and the DOM has been re-rendered. beforeDestroy - Called right before the Vue instance is destroyed. destroyed - Called after the Vue instance has been destroyed. There are two newer Vue 2 LifeCycle methods: activated - Used for , when a component inside is toggled on. deactivated - Used for , when a component inside is toggled off. errorCaptured - Called when an error from any descendent component is captured.Unmounting in Vue 3
In Vue 3 beforeDestroy() can also be written as beforeUnmount(), and destroyed() can be written as unmounted()
<template> <button class="button"> <slot>Submit</slot> --- slot with default value </button> </template>
// -- BaseButton with custom content -- <BaseButton>Cancel</BaseButton>
v-slot:
OR #
BlogLayout.vue <slot name="header"></slot>
App.vue <template> <template v-slot:header> --- header is a name of slot </template> </template>OR
App.vue <template> <template v-slot:[slotName]> --- slotName is a JS variable that holds a name of slot </template> </template>
v-model
For input
element is a shortcut for
listening for input event and binding the value ---> @input=""
value=""
<form @submit.prevent="addToCart">...</form> --- prevent is preventDefault()
v-model
Modifiers
<input name="myField" type="text" v-model.number="myField" /> --- force to return number value
<input name="firstName" type="text" v-model.trim="firstName" /> --- force to return trimmed value
<div class="form-control" :class="{ invalid: userNameValidity === 'invalid'}"> <label for="user-name">Your Name</label> <input id="user-name" name="user-name" type="text" v-model="userName" @blur="validateInput" /> <p v-if="userNameValidity === 'invalid'">Please enter a valid name</p> </div>
data() { return { userNameValidity: 'pending' } },
methods: { validateInput() { if (this.userName.trim() === '') { // other way of trim - v-model.trim()="userName" this.userNameValidity = 'invalid'; } else { this.userNameValidity = 'valid'; } } }
.form-control.invalid input { border-color: red; } .form-control.invalid label { color: red; }
v-model
converts input of number type into the number
<input id="age" name="age" type="number" v-model="userAge" /> --- userAge is of type number
<input id="age" name="age" type="number" v-model="userAge" ref="ageInput" /> --- ref accesses the native DOM element ... console.log(this.$refs.ageInput.value); --- the value using ref is of type string (and not number)
<input type="checkbox" id="confirm-term" name="confirm-term" v-model="termConfirm">
data() { return { termConfirm: false } },
<div> <input id="interest-news" name="interest" value="news" type="checkbox" v-model="interest" /> <label for="interest-news">News</label> </div> <div> <input id="interest-tutorials" name="interest" type="checkbox" value="tutorials" v-model="interest" /> <label for="interest-tutorials">Tutorials</label> </div>
data() { return { interest: [] } }
<div> <input id="how-video" name="how" type="radio" value="video" v-model="how" /> <label for="how-video">Video Courses</label> </div> <div> <input id="how-blogs" name="how" type="radio" value="blogs" v-model="how" /> <label for="how-blogs">Blogs</label> </div>
data() { return { how: null } },
.eslintrc.js
file
extends: [ ... "plugin:prettier/recommended", ],
%APPDATA%\Code\User
folder
"vetur.validation.template": false
"eslint.validate": [ { "language": "vue", "autoFix": true }, { "language": "html", "autoFix": true }, { "language": "javascript", "autoFix": true } ],
"eslint.autoFixOnSave": true,
"editor.formatOnSave": true,
vue.config.js
in the root folder of the project
module.exports = { publicPath: "/projects/226/vue2", };
router
add
const router = new VueRouter({ mode: "history", base: process.env.BASE_URL, routes, });
npm run build