<body>
<tweets>
<tweet text="This is my 1st tweet!"><tweet>
<tweet text="This is my 2nd tweet!"><tweet>
<tweet text="This is my 3rd tweet!"><tweet>
</tweets>
</body><!-- tweet component -->
<div class="tweet-container">
<div class="username">@johndoe</div>
<div class="tweet-text">This is my 1st tweet!</div>
</div><div id="app">
<span>Hello {{ name }}!</span>
</div>new Vue({
el: '#app',
data() {
return {
name: 'John Doe'
}
}
})<div id="app">
<span>Hello {{ name }}!</span>
</div><span>{{ const name = 'John Doe' }}</span><button v-bind:disabled="buttonDisabled">Click me</button>
<!-- or -->
<button :disabled="buttonDisabled">Click me</button>// ...
data() {
return {
buttonDisabled: true
}
}<a :href="url">Google</a>// ...
data() {
return {
url: 'https://www.google.com'
}
}<div :class="{ 'is-active': isActive }"></div>// ...
data() {
return {
isActive: true
}
}<div :style="{ width: width, backgroundColor: red }"></div>// ...
data() {
return {
width: '100px',
red: '#FF0000'
}
}<div v-if="quantity === 0">Nothing</div>
<div v-else-if="quantity > 5">Some</div>
<div v-else-if="quantity > 10">Some more</div>
<div v-else>Many</div><div v-show="isVisible">Hey there!</div><ul>
<li v-for="name in names">{{ name }}</li>
</ul>// ...
data() {
return {
names: ['John', 'Jane', 'Alice']
}
}<ul>
<li v-for="(name, index) in names">
{{ index }} - {{ name }}
</li>
</ul>// ...
data() {
return {
names: ['John', 'Jane', 'Alice']
}
}<ul>
<li v-for="(prop, key) in user">
{{ key }}: {{ prop }}
</li>
</ul>// ...
data() {
return {
user: {
name: 'John',
age: 22,
state: 'CA, California'
}
}
}// Register before root Vue instance
Vue.component('hello-world', {
template: '<div>Hello, World!</div>'
})
new Vue({
el: '#app'
})<div id="app">
<hello-world></hello-world>
</div>const HelloWorld = {
template: '<div>Hello, World!</div>'
}
new Vue({
// ...
components: {
// Only available in parent's template
'hello-world': HelloWorld
}
})<template>
<span>{{ message }}</span>
</template>
<script>
export default {
props: ['message']
})
</script>
<!-- If registered as HelloWorld component -->
<HelloWorld message="Hello, World!"></HelloWorld>Hello, World!
(does not apply to .vue files)
<HelloWorld v-bind:message="helloMessage"></HelloWorld>
<!-- or -->
<HelloWorld :message="helloMessage"></HelloWorld>// ...
props: {
propA: Number,
propB: [String, Number],
propC: {
type: String,
required: true
},
propD: {
type: Number,
default: 100
}
}<Header />
<Checkout>
<Item name="product1"></Item>
<Item name="product2"></Item>
<Item name="product3"></Item>
</Checkout><!-- Checkout component template -->
<div>
<h2>Checkout</h2>
<slot>
<!-- only visible if no content to be distributed -->
<span>There's no item in your cart</span>
</slot>
</div>
<div>
<h2>Checkout</h2>
<span>product1</span>
<span>product2</span>
<span>product3</span>
</div>
<Checkout>
<Item name="product1"></Item>
<Item name="product2"></Item>
<Item name="product3"></Item>
</Checkout><div>
{{ message.split('').reverse().join('') }}
</div><div>
<span>{{ message }}</span>
<span>{{ reversedMessage }}</span>
</div>// ...
data() {
return { message: 'Hello, World!' }
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}Hello, World! !dlroW ,olleH
<div>
<span>{{ message }}</span>
<span>{{ reversedMessage }}</span>
</div>Hello, World! !dlroW ,olleH
this.reversedMessage // Ok -> !dlroW ,olleH
this.reversedMessage() // Error<span>{{ greetings() }}</span>// ...
data() {
return { name: 'John Doe' }
},
methods: {
greetings() {
return `Hello, ${this.name}!`
}
}<span>{{ greetings }}</span>// ...
data() {
return { name: 'John Doe' }
},
computed: {
greetings() {
return `Hello, ${this.name}!`
}
}<span>{{ counter }}</span>
<button v-on:click="add">Add 1</button>
<!-- or -->
<button @click="add">Add 1</button>// ...
data() {
return { counter: 0 }
},
methods: {
add() {
this.counter++
}
}<button @click="hello('John')">Hello</button>// ...
methods: {
hello(name) {
console.log(`Hello ${name}`)
}
}<button @click="intercept('hello', $event)">
Intercept me!
</button>// ...
methods: {
intercept(msg, $event) {
console.log(msg)
$event.preventDefault()
}
}<!-- Child component template -->
<button @click="add">Add 1</button>// Child component instance
// ...
methods: {
add() {
this.$emit('addNumber', 1)
}
}<!-- Parent component template -->
<Child @addNumber="add"></Child>// Parent component instance
// ...
methods: {
add(value) { // Here value is 1
this.counter += value
}
}import Vue from 'Vue'
import App from './App'
// vm: ViewModel
const vm = new Vue({
el: '#app',
template: '<App />',
components: { App },
// other options
})const vm = new Vue({
data() {
return { one: 1 }
}
})
vm.two = 2 // will not render a view update!const vm = new Vue({
data() {
return { one: 1 }
},
watch: {
one(newVal, oldVal) {
// do something
}
}
})
vm.one = 2 // will trigger watch functionconst vm = new Vue({
// ...
watch: {
one: {
immediate: true,
handler(newVal, oldVal) {
/* will execute immediately
and on each update */
}
}
}
})const vm = new Vue({
// ...
beforeCreate() { ... },
created() { ... },
beforeMount() { ... },
mounted() { ... },
beforeUpdate() { ... },
updated() { ... },
beforeDestroy() { ... },
destroyed() { ... }
})# install vue-cli
npm install -g @vue/cli
# create a new project with command line
vue create hello-vue
# create a new project with web UI
vue uiimport Vue from 'vue'
import App from './App'
import '@/assets/css/style.css'
import { movies } from '@/assets/json/movies.json'<img src="require('@/assets/img/image.jpg')">data () {
return {
// configured in vue.config.js
baseUrl: process.env.BASE_URL
}
}<img :src="`${baseUrl}image.png`">.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git# .env.development
VUE_APP_DEBUG_MODE=true# .env.production
VUE_APP_DEBUG_MODE=false// Application code
console.log(process.env.VUE_APP_DEBUG_MODE);
// true when `npm run serve`
// false when `npm run build`HEADER
MENU
/foo
/bar
/baz
npm install --save vue-routerimport Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)import Router from 'vue-router'
import Foo from '@/components/Foo.vue'
import Bar from '@/components/Bar.vue'
const router = new Router({
routes: [
{ name: 'foo', path: '/foo', component: Foo },
{ name: 'bar', path: '/bar', component: Bar }
]
})
new Vue({ el: '#app', router, /* ... */ })<template>
<Header />
<Menu />
<!-- components will be dynamically
rendered here according to the route -->
<router-view />
</template>
<router-view />
<template>
<!-- <router-link> will be rendered as <a> -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</template>
// ...
methods: {
goToFoo() {
this.$router.push('/foo')
}
}// ...
routes: [
// dynamic segments start with a colon
{ path: '/user/:id', component: User }
]<!-- User component -->
<template>
<div>Hello user {{ $route.params.id }}</div>
</template>http://localhost:3000/user/1
http://localhost:3000/user/2
routes: [
{ path: '/user/:id', component: User,
children: [
{ path: 'profile', component: UserProfile },
{ path: 'posts', component: UserPosts }
]
}
]http://localhost:3000/user/1/profile
http://localhost:3000/user/1/posts
<!-- App component -->
<template>
<Header />
<router-view />
</template>
<!-- User component -->
<template>
Hello user {{ $route.params.id }}
<!-- Here is rendered
`UserProfile` / `UserPosts` component -->
<router-view />
</template>
this.$router.push({ name: 'user', params: { id: 1 } })
// /foo?search=new
this.$router.push({ path: 'foo', query: { search: 'new' } })<router-link :to="{ name: 'user', params: { id: 1 } }">
User 1
</router-link><template>
<form>
<input v-model="fullName">
<p>Fullname is {{ fullName }}</p>
</form>
</template><script>
data() {
return {
fullName: ''
}
}
</script><input
:value="fullName"
@input="fullName = $event.target.value"><input v-model="fullName"><input type="checkbox" v-model="checked"><input type="checkbox" value="John" v-model="checkedNames">
<input type="checkbox" value="Jane" v-model="checkedNames">
<!-- checkedNames will be [] or ["John"] or ["Jane"]
or ["John", "Jane"] --><input type="checkbox" value="John" v-model="name">
<input type="checkbox" value="Jane" v-model="name">
<input type="checkbox" value="Alice" v-model="name">
<!-- name will be "John" or "Jane" or "Alice" --><select v-model="user">
<option disabled value="">Select someone</option>
<option>John</option>
<option>Jane</option>
<option>Alice</option>
</select>
<!-- user will be "John" or "Jane" or "Alice" --><select v-model="selectedUser">
<option v-for="user in users" :value="user.id">
{{ user.name }}
</option>
</select>data() {
return {
selectedUser: 1,
users: [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Alice' }
]
}
}// Register a global custom directive called `v-focus`
Vue.directive('focus', {
inserted(el) {
el.focus()
}
})<input v-focus>bind
inserted
update
componentUpdate
unbind
inserted(el, binding, /* ... */) {
/*
* - el: the element the directive is bound to
* - binding: an object with the following properties:
* - name: the name of the directive without the `v-`
* - value: the value passed to the directive
* - oldValue: the previous value
*/
}<div v-color="#fff"></div>bind(el, binding) {
el.style.backgroundColor = binding.value
}<h1
v-greetings="{ text: 'Hello, World!', color: '#fff' }">
</h1>bind(el, binding) {
el.textContent = binding.value.text
el.style.backgroundColor = binding.value.color
}// Register a global filter called `uppercase`
Vue.filter('uppercase', function (value) {
if (!value) return ''
return value.toString().toUpperCase()
})<!-- greetings = 'Hello, World!' -->
<h1>{{ greetings | uppercase }}</h1>
<!-- HELLO, WORLD! --><!-- filters can be chained -->
<h1>{{ greetings | filterA | filterB }}</h1><!-- filters can take arguments -->
<h1>{{ price | currency(2, '$') }}</h1>Vue.filter('currency', function (price, format, symbol) {
// ...
})