OSDN Git Service

Regular updates
[twpd/master.git] / vue.md
1 ---
2 title: Vue.js
3 category: JavaScript
4 layout: 2017/sheet
5 updated: 2019-12-26
6 weight: -10
7 intro: |
8   [Vue.js](https://vuejs.org/) is an open-source Model–view–viewmodel JavaScript framework for building user interfaces and single-page applications.
9 ---
10
11 {%raw%}
12
13 Expressions
14 ----------
15 {: .-three-column}
16
17 ### Expressions
18
19 ```html
20 <div id="app">
21   <p>I have a {{ product }}</p>
22   <p>{{ product + 's' }}</p>
23   <p>{{ isWorking ? 'YES' : 'NO' }}</p>
24   <p>{{ product.getSalePrice() }}</p>
25 </div>
26 ```
27
28 See: [Delimiters](https://vuejs.org/v2/api/#delimiters)
29
30 ### Binding
31
32 ```html
33 <a v-bind:href="url">...</a>
34 ```
35
36 #### Shorthand syntax
37 ```html
38 <a :href="url">...</a>
39 ```
40 {: data-line="1"}
41
42 #### True or false will add or remove attribute
43 ```html
44 <button :disabled="isButtonDisabled">...
45 ```
46
47 #### If isActive is truthy, the class ‘active’ will appear
48 ```html
49 <div :class="{ active: isActive }">...
50 ```
51
52 #### Style color set to value of activeColor
53 ```html
54 <div :style="{ color: activeColor }">
55 ```
56
57 See: [v-bind](https://vuejs.org/v2/api/#v-bind)
58
59 ### Directives
60
61 #### Element inserted/removed based on truthiness
62 ```html
63 <p v-if="inStock">{{ product }}</p>
64 ```
65 ```html
66 <p v-else-if="onSale">...</p>
67 <p v-else>...</p>
68 ```
69
70 #### Toggles the display: none CSS property
71 ```html
72 <p v-show="showProductDetails">...</p>
73 ```
74
75 #### Two-way data binding
76 ```html
77 <input v-model="firstName" >
78 ```
79
80 | Method | Description |
81 | --- | --- |
82 | `v-model.lazy="..."` | Syncs input after change event |
83 | `v-model.number="..."` | Always returns a number |
84 | `v-model.trim="..."` | Strips whitespace |
85
86 See: [Directives](https://vuejs.org/v2/api/#Directives)
87
88 ### Actions/Events
89
90 #### Calls addToCart method on component
91 ```html
92 <button v-on:click="addToCart">...
93 ```
94
95 #### Shorthand syntax
96 ```html
97 <button @click="addToCart">...
98 ```
99 {: data-line="1"}
100
101 #### Arguments can be passed
102 ```html
103 <button @click="addToCart(product)">...
104 }
105 ```
106
107 #### To prevent default behavior (e.g. page reload)
108 ```html
109 <form @submit.prevent="addProduct">...
110 ```
111
112 #### Only trigger once
113 ```html
114 <img @mouseover.once="showImage">...
115 ```
116
117 | Method | Description |
118 | --- | --- |
119 | `.stop` | Stop all event propagation |
120 | `.self ` | Only trigger if event.target is element itself |
121
122 #### Keyboard entry example
123 ```html
124 <input @keyup.enter="submit">
125 ```
126
127 #### Call onCopy when control-c is pressed
128 ```html
129 <input @keyup.ctrl.c="onCopy">
130 ```
131
132 See: [Events](https://vuejs.org/v2/guide/events.html)
133
134 ### List rendering
135
136 #### The `:key` is always recommended
137 ```html
138 <li v-for="item in items"
139     :key="item.id">
140   {{ item }}
141 </li>
142 ```
143 {: data-line="2"}
144
145 #### To access the position in the array
146 ```html
147 <li v-for="(item, index) in items">...
148 ```
149
150 #### To iterate through objects
151 ```html
152 <li v-for="(value, key) in object">...
153 ```
154
155 #### Using `v-for` with a component
156 ```html
157 <cart-product v-for="item in products"
158               :product="item"
159               :key="item.id">
160 ```
161
162 See: [List Rendering](https://vuejs.org/v2/guide/list.html)
163
164
165 Component
166 --------
167
168 ### Component anatomy
169
170 ```js
171 Vue.component('my-component', {
172   components: {
173     // Components that can be used in the template
174     ProductComponent,
175     ReviewComponent
176   },
177   props: {
178     // The parameters the component accepts
179     message: String,
180     product: Object,
181     email: {
182       type: String,
183       required: true,
184       default: "none"
185       validator: function (value) {
186         // Should return true if value is valid
187       }
188     }
189   },
190   data: function() {
191     // `data` must be a function
192     return {
193       firstName: 'Vue',
194       lastName: 'Mastery'
195     }
196   },
197   computed: {
198     // Return cached values until dependencies change
199     fullName: function () {
200       return this.firstName + ' ' + this.lastName
201     }
202   },
203   watch: {
204     // Called when firstName changes value
205     firstName: function (value, oldValue) { ... }
206   },
207   methods: { ... },
208   template: '<span>{{ message }}</span>',
209   // Can also use backticks in `template` for multi-line
210 })
211 ```
212 {: data-line="3, 8, 16, 21, 28, 34, 39"}
213
214 See: [Components Basics](https://vuejs.org/v2/guide/components.html)
215
216 ### Lifecycle hooks
217
218 | Method | Description |
219 | --- | --- |
220 | `beforeCreate` | After the instance has been initialized [#](https://vuejs.org/v2/api/#beforeCreate) |
221 | `created` | After the instance is created [#](https://vuejs.org/v2/api/#created) |
222 | `beforeMount` | Before the first render [#](https://vuejs.org/v2/api/#beforeMount) |
223 | `mounted` | After the instance has been mounted [#](https://vuejs.org/v2/api/#mounted) |
224 | `beforeUpdate` | When data changes, before the DOM is patched [#](https://vuejs.org/v2/api/#beforeUpdate) |
225 | `updated` | After a data change [#](https://vuejs.org/v2/api/#updated) |
226 | `beforeDestroy` | Before the instance is destroyed [#](https://vuejs.org/v2/api/#beforeDestroy) |
227 | `destroyed` | After a Vue instance has been destroyed [#](https://vuejs.org/v2/api/#destroyed) |
228
229 See: [Lifecycle Hooks](https://vuejs.org/v2/api/#Options-Lifecycle-Hooks)
230
231 ### Custom events
232
233 #### Set listener on component, within its parent
234 ```html
235 <button-counter v-on:incrementBy="incWithVal">
236 ```
237
238 #### Inside parent component
239 ```js
240 methods: {
241   incWithVal: function (toAdd) { ... }
242 }
243 ```
244
245 #### Inside button-counter template
246 ```js
247 this.$emit(
248     'incrementBy', // Custom event name
249     5 // Data sent up to parent
250   )
251 ```
252
253 Use props to pass data into child components,
254 custom events to pass data to parent elements.
255
256 See: [Custom Events](https://vuejs.org/v2/guide/components-custom-events.html)
257
258 Single file components
259 --------
260
261 ### Single file
262 ```html
263 <template>
264   <p>{{ greeting }} World!</p>
265 </template>
266
267 <script>
268 module.exports = {
269   data: function () {
270     return {
271       greeting: 'Hello'
272     }
273   }
274 }
275 </script>
276
277 <style scoped>
278 p {
279   font-size: 2em;
280   text-align: center;
281 }
282 </style>
283 ```
284
285 See: [Single File Components](https://vuejs.org/v2/guide/single-file-components.html)
286
287 ### Separation
288 ```html
289 <template>
290   <div>This will be pre-compiled</div>
291 </template>
292 <script src="./my-component.js"></script>
293 <style src="./my-component.css"></style>
294 ```
295
296 See: [What About Separation of Concerns?](https://vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns)
297
298 Slots
299 --------
300
301 ### Using a single slot
302
303 #### Component template
304 ```html
305 <div>
306   <h2>I'm a title</h2>
307   <slot>
308     Only displayed if no slot content
309   </slot>
310 </div>
311 ```
312 {: data-line="3,4,5"}
313
314 #### Use of component with data for slot
315 ```html
316 <my-component>
317   <p>This will go in the slot</p>
318 </my-component>
319 ```
320 {: data-line="2"}
321
322 See: [Slots](https://vuejs.org/v2/guide/components-slots.html)
323
324 ### Multiple slots
325
326 #### Component template
327 ```html
328 <div class="container">
329   <header>
330     <slot name="header"></slot>
331   </header>
332   <main>
333     <slot>Default content</slot>
334   </main>
335   <footer>
336     <slot name="footer"></slot>
337   </footer>
338 </div>
339 ```
340 {: data-line="3,6,9"}
341
342 #### Use of component with data for slots
343 ```html
344 <app-layout>
345   <h1 slot="header">Page title</h1>
346   <p>the main content.</p>
347   <p slot="footer">Contact info</p>
348 </app-layout>
349 ```
350 {: data-line="2,3,4"}
351
352 See: [Slots](https://vuejs.org/v2/guide/components-slots.html)
353
354 Also see
355 --------
356
357 * [Vue CLI](https://cli.vuejs.org/) _(cli.vuejs.org)_
358 * [Vue Router](https://router.vuejs.org/) _(router.vuejs.org)_
359 * [Vue DevTools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en) _(chrome.google.com)_
360 * [Nuxt.js](https://nuxtjs.org/) _(nuxtjs.org)_
361 * [Vue.js v1.0.28 cheatsheet](vue@1.0.28/) _Legacy version_
362
363 {%endraw%}