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 #### To prevent default behavior (e.g. page reload)
107 ```html
108 <form @submit.prevent="addProduct">...
109 ```
110
111 #### Only trigger once
112 ```html
113 <img @mouseover.once="showImage">...
114 ```
115
116 | Method | Description |
117 | --- | --- |
118 | `.stop` | Stop all event propagation |
119 | `.self ` | Only trigger if event.target is element itself |
120
121 #### Keyboard entry example
122 ```html
123 <input @keyup.enter="submit">
124 ```
125
126 #### Call onCopy when control-c is pressed
127 ```html
128 <input @keyup.ctrl.c="onCopy">
129 ```
130
131 See: [Events](https://vuejs.org/v2/guide/events.html)
132
133 ### List rendering
134
135 #### The `:key` is always recommended
136 ```html
137 <li v-for="item in items"
138     :key="item.id">
139   {{ item }}
140 </li>
141 ```
142 {: data-line="2"}
143
144 #### To access the position in the array
145 ```html
146 <li v-for="(item, index) in items">...
147 ```
148
149 #### To iterate through objects
150 ```html
151 <li v-for="(value, key) in object">...
152 ```
153
154 #### Using `v-for` with a component
155 ```html
156 <cart-product v-for="item in products"
157               :product="item"
158               :key="item.id">
159 ```
160
161 See: [List Rendering](https://vuejs.org/v2/guide/list.html)
162
163
164 Component
165 --------
166
167 ### Component anatomy
168
169 ```js
170 Vue.component('my-component', {
171   components: {
172     // Components that can be used in the template
173     ProductComponent,
174     ReviewComponent
175   },
176   props: {
177     // The parameters the component accepts
178     message: String,
179     product: Object,
180     email: {
181       type: String,
182       required: true,
183       default: "none"
184       validator: function (value) {
185         // Should return true if value is valid
186       }
187     }
188   },
189   data: function() {
190     // `data` must be a function
191     return {
192       firstName: 'Vue',
193       lastName: 'Mastery'
194     }
195   },
196   computed: {
197     // Return cached values until dependencies change
198     fullName: function () {
199       return this.firstName + ' ' + this.lastName
200     }
201   },
202   watch: {
203     // Called when firstName changes value
204     firstName: function (value, oldValue) { ... }
205   },
206   methods: { ... },
207   template: '<span>{{ message }}</span>',
208   // Can also use backticks in `template` for multi-line
209 })
210 ```
211 {: data-line="3, 8, 16, 21, 28, 34, 39"}
212
213 See: [Components Basics](https://vuejs.org/v2/guide/components.html)
214
215 ### Lifecycle hooks
216
217 | Method | Description |
218 | --- | --- |
219 | `beforeCreate` | After the instance has been initialized [#](https://vuejs.org/v2/api/#beforeCreate) |
220 | `created` | After the instance is created [#](https://vuejs.org/v2/api/#created) |
221 | `beforeMount` | Before the first render [#](https://vuejs.org/v2/api/#beforeMount) |
222 | `mounted` | After the instance has been mounted [#](https://vuejs.org/v2/api/#mounted) |
223 | `beforeUpdate` | When data changes, before the DOM is patched [#](https://vuejs.org/v2/api/#beforeUpdate) |
224 | `updated` | After a data change [#](https://vuejs.org/v2/api/#updated) |
225 | `beforeDestroy` | Before the instance is destroyed [#](https://vuejs.org/v2/api/#beforeDestroy) |
226 | `destroyed` | After a Vue instance has been destroyed [#](https://vuejs.org/v2/api/#destroyed) |
227
228 See: [Lifecycle Hooks](https://vuejs.org/v2/api/#Options-Lifecycle-Hooks)
229
230 ### Custom events
231
232 #### Set listener on component, within its parent
233 ```html
234 <button-counter v-on:incrementBy="incWithVal">
235 ```
236
237 #### Inside parent component
238 ```js
239 methods: {
240   incWithVal: function (toAdd) { ... }
241 }
242 ```
243
244 #### Inside button-counter template
245 ```js
246 this.$emit(
247     'incrementBy', // Custom event name
248     5 // Data sent up to parent
249   )
250 ```
251
252 Use props to pass data into child components,
253 custom events to pass data to parent elements.
254
255 See: [Custom Events](https://vuejs.org/v2/guide/components-custom-events.html)
256
257 Single file components
258 --------
259
260 ### Single file
261 ```html
262 <template>
263   <p>{{ greeting }} World!</p>
264 </template>
265
266 <script>
267 module.exports = {
268   data: function () {
269     return {
270       greeting: 'Hello'
271     }
272   }
273 }
274 </script>
275
276 <style scoped>
277 p {
278   font-size: 2em;
279   text-align: center;
280 }
281 </style>
282 ```
283
284 See: [Single File Components](https://vuejs.org/v2/guide/single-file-components.html)
285
286 ### Separation
287 ```html
288 <template>
289   <div>This will be pre-compiled</div>
290 </template>
291 <script src="./my-component.js"></script>
292 <style src="./my-component.css"></style>
293 ```
294
295 See: [What About Separation of Concerns?](https://vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns)
296
297 Slots
298 --------
299
300 ### Using a single slot
301
302 #### Component template
303 ```html
304 <div>
305   <h2>I'm a title</h2>
306   <slot>
307     Only displayed if no slot content
308   </slot>
309 </div>
310 ```
311 {: data-line="3,4,5"}
312
313 #### Use of component with data for slot
314 ```html
315 <my-component>
316   <p>This will go in the slot</p>
317 </my-component>
318 ```
319 {: data-line="2"}
320
321 See: [Slots](https://vuejs.org/v2/guide/components-slots.html)
322
323 ### Multiple slots
324
325 #### Component template
326 ```html
327 <div class="container">
328   <header>
329     <slot name="header"></slot>
330   </header>
331   <main>
332     <slot>Default content</slot>
333   </main>
334   <footer>
335     <slot name="footer"></slot>
336   </footer>
337 </div>
338 ```
339 {: data-line="3,6,9"}
340
341 #### Use of component with data for slots
342 ```html
343 <app-layout>
344   <h1 slot="header">Page title</h1>
345   <p>the main content.</p>
346   <p slot="footer">Contact info</p>
347 </app-layout>
348 ```
349 {: data-line="2,3,4"}
350
351 See: [Slots](https://vuejs.org/v2/guide/components-slots.html)
352
353 Also see
354 --------
355
356 * [Vue CLI](https://cli.vuejs.org/) _(cli.vuejs.org)_
357 * [Vue Router](https://router.vuejs.org/) _(router.vuejs.org)_
358 * [Vue DevTools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en) _(chrome.google.com)_
359 * [Nuxt.js](https://nuxtjs.org/) _(nuxtjs.org)_
360 * [Vue.js v1.0.28 cheatsheet](vue@1.0.28/) _Legacy version_
361
362 {%endraw%}