Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --DOM manipulation--
- (angular syntax) [href]="" -> v-bind:href=""
- v-once: to disable re-rendering
- v-html="": pass dynamic html string
- v-on:click="" -> listen to events
- @click.native -> adds click event listener to the native element
- v-on:mousemove.stop="" -> event modifier, stops propagation
- v-on:mousemove.prevent="" -> prevent default
- v-on:keyup.enter.space="" -> chaining keyevent modifiers
- v-model="" -> two way binding
- //sharthands
- v-on:click -> @click
- v-bind:href -> :href
- :class="{ 'red' : isClicked }" -> class binding
- :class="[color, { 'red' : isClicked }]" -> class binding with dynamic input name (color), array syntax
- :style="{ backgroundColor: 'red' }" -> style binding
- :style="[myStyle, { backgroundColor: 'red' }]" -> array syntax
- ************************************
- --rendering lists, conditions, for loop in template--
- v-if="cond" -> conditionally show/hide dom elements
- v-else -> refers to the latest v-if placed before it
- // with template that groups elements
- <template v-if="show"><h1></h1><h3></h3></template>
- v-show="cond" -> add display:none style, but element remains in dom
- v-for="(item, i) in items" -> loop through the items array, i gets the index value. Order is important. Also works with <template></template>
- // loop through objects
- v-for="(value, key, index) in person" -> key iteration can be done by nesting v-for
- // loop given times
- v-for="n in 10" -> loop 10 times
- // keep tracking the whole element when using v-for (recommended)
- v-for="(item, i) in items" :key="item"
- ***********************************
- --The vue instance--
- Multiple vue instances can be placed. An instance can be accessed outside after stored in a variable.
- var vm = new Vue({data: {title = 'asd'}}). In instance 2: vm.title = 'ASD'; A new prop created outside won't be watchable (vue wont watch it).
- $el: referts to html template code. div#app
- $data: holds data props. vm.$data.title equals vm.title
- $refs: ref tag should be added to html element. ref="myButton". After that this element is accessible by this.$refs.myButton. It's only changing the dom and it's not reactive because vue's template isn't affected.
- $mount(): vm.$mount('#app'). Replaces new Vue({el: '#app'});
- template: in Vue instance, simple template can be placed like <h1>Hello</h1>. Then vm.$mount('#app3') will render this template. Also works with document.getElementById('app3').appendChild(vm.$el). Result is the same. $el means the template.
- Components: Vue.component('hello', {template: <h1>Hello</h1>}); // hello is the selector
- Usage: <hello></hello>
- How vue updates the dom: vue uses virtual dom. Only updates partials of the real dom where changes happened.
- Lifecycle hooks:
- - beforeCreate() (new Vue)
- - created()
- - beforeMount()
- - mounted()
- - beforeUpdate(): before change detection runs
- - updated()
- - beforeDestroy()
- - destroyed() (this.$destroy() call explicitly)
- ***********************************
- --CLI--
- npm i -g vue-cli
- vue init webpack-simple project-name
- render: h => h(App) -> accepts a vue template
- ***********************************
- --Components--
- <style scoped></style> -> to encapsulate style
- Parent to child communication: using props. In parent, props: ['name'] then use it {{ name }}. To pass it to child: <child :name="Max"></child> (or v-bind:name) where name is an inner prop.
- Prop validation: prop: {name: [String, Array]} or prop: {name: {type: String, required: true}} or prop: {name: {type: String, default: 'Max'}}
- Child to parent: this.$emit('eventName', value). At parent: @eventName="someMethod"
- Between siblings: 4 ways to do that.
- 1. with $emit to parent, then parent sends the new value to the destination child
- 2. handle functions
- 3. with event bus (services). At main.js: export const eventBus = new Vue(); At the place where is should be used, import it, then call eventBus.$emit(). At the callback place call eventBus.$on()
- 4. vuex
- Slots to pass inner content:
- <slot></slot> similar to angular's ng-content.
- Styling: only applies when style has been written at child component. Written style in parent will be skipped.
- Multiple slots: <slot name="something"></slot>. At parent: <h2 slot="something"></h2>
- Default slot: an unnamed slot next to a named one.
- Slot with default value: <slot name="asd">This content will be overwritten when 'asd' slot is created in parent.</slot>
- Dynamic component:
- <component :is="componentName">
- <p>Default content</p>
- </component>
- When component is changed, the old will be destroyed and its state resets.
- To keep them alive: wrap <component> with <keep-alive></keep-alive>. destroy hook won't be called in this case.
- Dynamic component's lifecycle hooks: activated and deactivated. At the component declare activated() and deactivated() methods, vue handles them as hooks.
- ***********************************
- --Forms--
- Using v-model: v-model can be used on any element which has value prop and input event.
- v-model.lazy -> updates the value on change event instead of input event
- v-model.trim -> remove white space
- v-model.number -> conver to number
- checkbox/radio button: adding v-model with the same name ensures that vue handles the checkboxes as an array, radio boxes as group
- ***********************************
- --Directives--
- some other built in:
- v-text: innertext
- v-html: innerhtml
- directive hooks:
- - bind(el, binding, vnode)
- - inserted(el, binding, vnode)
- - update(el, binding, vnode, oldVnode)
- - componentUpdated(el, binding, vnode, oldVnode)
- - unbind(el, binding, vnode)
- new directive:
- Vue.directive('highlight', { bind(el, binding, vnode) { el.style.backgroundColor = binding.value; } })
- on html element: v-highlight="red"
- or: v-highlight:background="red". In the directive, the binding.arg will hold the 'background' argument
- with modifiers: v-highlight:background.delayed="red" -> access the modifier: binding.modifiers['delayed']
- registering directives locally: with the directives: { 'local-highlight': { bind()... } }
- passing more complex input: { mainColor: 'red', blinking: false }, acces it: binding.value.mainColor
- ***********************************
- --Filters and mixins--
- Filters:
- register globally: Vue.filter('toUppercase', (value) => value.toUppercase());
- In component locally: filters: { toUppercase(value) { return value.toUppercase(); } }
- usage: {{ text | toUppercase }}
- filter chaining: {{ text | toUppercase | toLowercase }} -> toLowercase will receive the uppercase version of the text
- filter alternative -> computed props:
- computed: {
- filteredFruits() { return this.fruits.filter(...); }
- }
- usage: v-for="f in filteredFruits"
- benefits: it's more performant
- Mixins: used for code reusability in .js files just like util functions.
- In component:
- mixins: [fruitMixin]
- Vue merges the mixin data with the component data: mixin has its own lifecycle hooks and they get called before the component boots.
- Global mixins: Vue.mixin(). Only in special cases because the global mixin is merged into each component.
- Order: global mixin -> local mixin -> component code
- Scope: data placed in mixins are uniq in each mixin.
- ***********************************
- --Animations--
- <transition> element: only used for one element.
- Transition css classes: *-enter for 1 frame, after that *-enter-active & *-leave, after that *-leave-active. Default css class: v-enter if no name is supplied.
- <transition name="fade" type="animation" appear></transition> then add css class: .fade-enter, .fade-enter-active, .fade-leave, .fade-leave-active.
- type: animation || transition. Vue waits until the animations or transition finishes.
- appear: animate on page load.
- Add custom class names: <transition enter-class="..." enter-active-class="..." leave-class="" leave-active-class="">. Appear won't work in this case.
- name, type with bind -> :name="variable"
- Transition between multiple element: by adding the 'key' attribute. v-show won't work. Use v-if.
- mode="out-in" or "in-out" the handle the element removal smoothness
- JavaScript hooks:
- - before-enter -> @before-enter
- - enter
- - after-enter
- - after-enter-cancelled
- - before-leave
- - leave
- - after-leave
- - after-leave-cancelled
- beforeEnter(el)
- enter(el, done) { console.log('enter'); done(); }
- :css="false" -> don't look for css classes, use js instead
- <transition-group name="slide"> -> for list (multiple elements can be placed inside it)
- ***********************************
- --HTTP--
- With vue-resource package/axios.
- ***********************************
- --Router--
- With vue-router package. Vue.use(VueRouter);
- export const routes = { path: '/user', component: User }
- const router = new VueRouter({routes});
- new Vue({el.., router});
- in template: <router-view>
- Routing modes: hash vs history
- hash: easier config on server side
- history: hosting server needs to be configured to serve index.html all the time
- <router-link to="path"> will wrap an <a> tag
- Styling the active link: <router-link to="path" tag="li" active-class="active">
- Exact path: <router-link to="path" exact>
- Navigation in code: this.$router.push(path). path can be string or object {path: '...'}
- Route parameters: { path: '/user/:id', component: User }
- Get param: this.$router.params.id
- Watch for router changes:
- watch: {'$route'(to, from) {this.id = to.params.id;} }
- Child routes: { path: '/user', component: User, children: [{path: ':id', component: 'UserUniq'}] }
- Named routes: { path: '/user', component: User, name: 'userEdit' }, in template: <router-link to="{name: userEdit, params: {id: $route.params.id}}"
- Query params: <router-link to="{query: {locale: 'en'}}" -> $route.query.locale
- Naming router views:
- <router-view name="v1">
- { path: '', name: 'home', components: { default: Home, v1: 'V1Comp' } }
- Redirecting: {path: '...', redirect: '...'}
- Wildcards: { path: '*', redirect: '/' }
- Route animations:
- <transition name="slide" mode="out-in"><router-view>... then add css classes
- Fragments: <router-link to="{name: userEdit, fragment: {data: '#data'}"
- Scroll behavior: in the new VueRouter instance:
- scrollBehavior(to, from, savedPosition) {return: x: 0, y: 700 }} or return savedPosition
- Guards:
- router.beforeEach((to, from, next) => {next(false || void || {params..});}) -> global before each
- or in the routes config: beforeEnter((to, from, next) => {next()})
- or in the component: beforeRouteEnter(to, from, next) {next()} -> can't access component props here. next can have a callback: next(vm => vm.something). In this case props are available.
- beforeRouteLeave(to, from, next) {if (this.confirmed) {next(true)}} in component code.
- ***********************************
- --Vuex--
- export const store = new Vuex.Store({
- state: {}
- getters: {},
- mutations: {},
- actions: {},
- modules {}
- })
- mapGetters:
- computed: { ...mapGetters(['prop-name': getterFn])}
- Mutations: this.$store.commit('increment') -> sync methods
- mapMutations
- Actions: for async tasks.
- actions: {increment: context => setTimeout(() => context.commit('increment'), 2000)}
- this.$store.dispatch('increment', arg)
- mapActions
- Modules: separate state, getters, mutations, actions and export default { state, mutations, getters, actions }
Add Comment
Please, Sign In to add comment