attilan

Vue basics

Jan 15th, 2020
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.13 KB | None | 0 0
  1. --DOM manipulation--
  2.  
  3. (angular syntax) [href]="" -> v-bind:href=""
  4.  
  5. v-once: to disable re-rendering
  6.  
  7. v-html="": pass dynamic html string
  8.  
  9. v-on:click="" -> listen to events
  10. @click.native -> adds click event listener to the native element
  11.  
  12. v-on:mousemove.stop="" -> event modifier, stops propagation
  13. v-on:mousemove.prevent="" -> prevent default
  14.  
  15. v-on:keyup.enter.space="" -> chaining keyevent modifiers
  16.  
  17. v-model="" -> two way binding
  18.  
  19. //sharthands
  20. v-on:click -> @click
  21. v-bind:href -> :href
  22.  
  23. :class="{ 'red' : isClicked }" -> class binding
  24. :class="[color, { 'red' : isClicked }]" -> class binding with dynamic input name (color), array syntax
  25.  
  26. :style="{ backgroundColor: 'red' }" -> style binding
  27. :style="[myStyle, { backgroundColor: 'red' }]" -> array syntax
  28.  
  29. ************************************
  30.  
  31. --rendering lists, conditions, for loop in template--
  32.  
  33. v-if="cond" -> conditionally show/hide dom elements
  34. v-else -> refers to the latest v-if placed before it
  35.  
  36. // with template that groups elements
  37. <template v-if="show"><h1></h1><h3></h3></template>
  38.  
  39. v-show="cond" -> add display:none style, but element remains in dom
  40.  
  41. v-for="(item, i) in items" -> loop through the items array, i gets the index value. Order is important. Also works with <template></template>
  42.  
  43. // loop through objects
  44. v-for="(value, key, index) in person" -> key iteration can be done by nesting v-for
  45.  
  46. // loop given times
  47. v-for="n in 10" -> loop 10 times
  48.  
  49. // keep tracking the whole element when using v-for (recommended)
  50. v-for="(item, i) in items" :key="item"
  51.  
  52. ***********************************
  53.  
  54. --The vue instance--
  55. Multiple vue instances can be placed. An instance can be accessed outside after stored in a variable.
  56. 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).
  57. $el: referts to html template code. div#app
  58. $data: holds data props. vm.$data.title equals vm.title
  59. $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.
  60. $mount(): vm.$mount('#app'). Replaces new Vue({el: '#app'});
  61. 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.
  62.  
  63. Components: Vue.component('hello', {template: <h1>Hello</h1>}); // hello is the selector
  64. Usage: <hello></hello>
  65.  
  66. How vue updates the dom: vue uses virtual dom. Only updates partials of the real dom where changes happened.
  67.  
  68. Lifecycle hooks:
  69. - beforeCreate() (new Vue)
  70. - created()
  71. - beforeMount()
  72. - mounted()
  73. - beforeUpdate(): before change detection runs
  74. - updated()
  75. - beforeDestroy()
  76. - destroyed() (this.$destroy() call explicitly)
  77.  
  78. ***********************************
  79.  
  80. --CLI--
  81. npm i -g vue-cli
  82. vue init webpack-simple project-name
  83.  
  84. render: h => h(App) -> accepts a vue template
  85.  
  86.  
  87. ***********************************
  88.  
  89. --Components--
  90. <style scoped></style> -> to encapsulate style
  91.  
  92. 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.
  93. Prop validation: prop: {name: [String, Array]} or prop: {name: {type: String, required: true}} or prop: {name: {type: String, default: 'Max'}}
  94.  
  95. Child to parent: this.$emit('eventName', value). At parent: @eventName="someMethod"
  96.  
  97. Between siblings: 4 ways to do that.
  98. 1. with $emit to parent, then parent sends the new value to the destination child
  99. 2. handle functions
  100. 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()
  101. 4. vuex
  102.  
  103. Slots to pass inner content:
  104. <slot></slot> similar to angular's ng-content.
  105. Styling: only applies when style has been written at child component. Written style in parent will be skipped.
  106. Multiple slots: <slot name="something"></slot>. At parent: <h2 slot="something"></h2>
  107. Default slot: an unnamed slot next to a named one.
  108. Slot with default value: <slot name="asd">This content will be overwritten when 'asd' slot is created in parent.</slot>
  109.  
  110. Dynamic component:
  111. <component :is="componentName">
  112. <p>Default content</p>
  113. </component>
  114. When component is changed, the old will be destroyed and its state resets.
  115. To keep them alive: wrap <component> with <keep-alive></keep-alive>. destroy hook won't be called in this case.
  116. Dynamic component's lifecycle hooks: activated and deactivated. At the component declare activated() and deactivated() methods, vue handles them as hooks.
  117.  
  118. ***********************************
  119.  
  120. --Forms--
  121. Using v-model: v-model can be used on any element which has value prop and input event.
  122.  
  123. v-model.lazy -> updates the value on change event instead of input event
  124. v-model.trim -> remove white space
  125. v-model.number -> conver to number
  126.  
  127. checkbox/radio button: adding v-model with the same name ensures that vue handles the checkboxes as an array, radio boxes as group
  128.  
  129. ***********************************
  130.  
  131. --Directives--
  132. some other built in:
  133. v-text: innertext
  134. v-html: innerhtml
  135.  
  136. directive hooks:
  137. - bind(el, binding, vnode)
  138. - inserted(el, binding, vnode)
  139. - update(el, binding, vnode, oldVnode)
  140. - componentUpdated(el, binding, vnode, oldVnode)
  141. - unbind(el, binding, vnode)
  142.  
  143. new directive:
  144. Vue.directive('highlight', { bind(el, binding, vnode) { el.style.backgroundColor = binding.value; } })
  145. on html element: v-highlight="red"
  146. or: v-highlight:background="red". In the directive, the binding.arg will hold the 'background' argument
  147. with modifiers: v-highlight:background.delayed="red" -> access the modifier: binding.modifiers['delayed']
  148.  
  149. registering directives locally: with the directives: { 'local-highlight': { bind()... } }
  150.  
  151. passing more complex input: { mainColor: 'red', blinking: false }, acces it: binding.value.mainColor
  152.  
  153. ***********************************
  154.  
  155. --Filters and mixins--
  156. Filters:
  157. register globally: Vue.filter('toUppercase', (value) => value.toUppercase());
  158. In component locally: filters: { toUppercase(value) { return value.toUppercase(); } }
  159. usage: {{ text | toUppercase }}
  160.  
  161. filter chaining: {{ text | toUppercase | toLowercase }} -> toLowercase will receive the uppercase version of the text
  162.  
  163. filter alternative -> computed props:
  164. computed: {
  165. filteredFruits() { return this.fruits.filter(...); }
  166. }
  167. usage: v-for="f in filteredFruits"
  168. benefits: it's more performant
  169.  
  170. Mixins: used for code reusability in .js files just like util functions.
  171. In component:
  172. mixins: [fruitMixin]
  173. Vue merges the mixin data with the component data: mixin has its own lifecycle hooks and they get called before the component boots.
  174. Global mixins: Vue.mixin(). Only in special cases because the global mixin is merged into each component.
  175. Order: global mixin -> local mixin -> component code
  176.  
  177. Scope: data placed in mixins are uniq in each mixin.
  178.  
  179. ***********************************
  180.  
  181. --Animations--
  182. <transition> element: only used for one element.
  183. 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.
  184.  
  185. <transition name="fade" type="animation" appear></transition> then add css class: .fade-enter, .fade-enter-active, .fade-leave, .fade-leave-active.
  186. type: animation || transition. Vue waits until the animations or transition finishes.
  187. appear: animate on page load.
  188.  
  189. Add custom class names: <transition enter-class="..." enter-active-class="..." leave-class="" leave-active-class="">. Appear won't work in this case.
  190.  
  191. name, type with bind -> :name="variable"
  192.  
  193. Transition between multiple element: by adding the 'key' attribute. v-show won't work. Use v-if.
  194.  
  195. mode="out-in" or "in-out" the handle the element removal smoothness
  196.  
  197. JavaScript hooks:
  198. - before-enter -> @before-enter
  199. - enter
  200. - after-enter
  201. - after-enter-cancelled
  202. - before-leave
  203. - leave
  204. - after-leave
  205. - after-leave-cancelled
  206.  
  207. beforeEnter(el)
  208. enter(el, done) { console.log('enter'); done(); }
  209.  
  210. :css="false" -> don't look for css classes, use js instead
  211.  
  212. <transition-group name="slide"> -> for list (multiple elements can be placed inside it)
  213.  
  214. ***********************************
  215.  
  216. --HTTP--
  217. With vue-resource package/axios.
  218.  
  219. ***********************************
  220.  
  221. --Router--
  222. With vue-router package. Vue.use(VueRouter);
  223. export const routes = { path: '/user', component: User }
  224. const router = new VueRouter({routes});
  225. new Vue({el.., router});
  226. in template: <router-view>
  227.  
  228. Routing modes: hash vs history
  229. hash: easier config on server side
  230. history: hosting server needs to be configured to serve index.html all the time
  231.  
  232. <router-link to="path"> will wrap an <a> tag
  233. Styling the active link: <router-link to="path" tag="li" active-class="active">
  234. Exact path: <router-link to="path" exact>
  235.  
  236. Navigation in code: this.$router.push(path). path can be string or object {path: '...'}
  237.  
  238. Route parameters: { path: '/user/:id', component: User }
  239. Get param: this.$router.params.id
  240.  
  241. Watch for router changes:
  242. watch: {'$route'(to, from) {this.id = to.params.id;} }
  243.  
  244. Child routes: { path: '/user', component: User, children: [{path: ':id', component: 'UserUniq'}] }
  245.  
  246. Named routes: { path: '/user', component: User, name: 'userEdit' }, in template: <router-link to="{name: userEdit, params: {id: $route.params.id}}"
  247.  
  248. Query params: <router-link to="{query: {locale: 'en'}}" -> $route.query.locale
  249.  
  250. Naming router views:
  251. <router-view name="v1">
  252. { path: '', name: 'home', components: { default: Home, v1: 'V1Comp' } }
  253.  
  254. Redirecting: {path: '...', redirect: '...'}
  255.  
  256. Wildcards: { path: '*', redirect: '/' }
  257.  
  258. Route animations:
  259. <transition name="slide" mode="out-in"><router-view>... then add css classes
  260.  
  261. Fragments: <router-link to="{name: userEdit, fragment: {data: '#data'}"
  262.  
  263. Scroll behavior: in the new VueRouter instance:
  264. scrollBehavior(to, from, savedPosition) {return: x: 0, y: 700 }} or return savedPosition
  265.  
  266. Guards:
  267. router.beforeEach((to, from, next) => {next(false || void || {params..});}) -> global before each
  268. or in the routes config: beforeEnter((to, from, next) => {next()})
  269. 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.
  270.  
  271. beforeRouteLeave(to, from, next) {if (this.confirmed) {next(true)}} in component code.
  272.  
  273. ***********************************
  274.  
  275. --Vuex--
  276. export const store = new Vuex.Store({
  277. state: {}
  278. getters: {},
  279. mutations: {},
  280. actions: {},
  281. modules {}
  282. })
  283.  
  284. mapGetters:
  285. computed: { ...mapGetters(['prop-name': getterFn])}
  286.  
  287. Mutations: this.$store.commit('increment') -> sync methods
  288. mapMutations
  289.  
  290. Actions: for async tasks.
  291. actions: {increment: context => setTimeout(() => context.commit('increment'), 2000)}
  292. this.$store.dispatch('increment', arg)
  293. mapActions
  294.  
  295. Modules: separate state, getters, mutations, actions and export default { state, mutations, getters, actions }
Add Comment
Please, Sign In to add comment