Skip to content

Commit 9008b29

Browse files
authored
Update (#762)
* Update unit-testing-vue-components.md (#1623) * Update v-for list example (#1628) * Add presentation role to style-only li item * fix: code snippet language (close #1617) (#1626) * Update todo-list-example for a11y (#1630) * Update todo-list-example for a11y * Implement review suggestions * Use explicit label instead of aria-label * Move v-model directive to top for improved readability * change NODE_ENV to follow recommendations from webpack (#1622) * change NODE_ENV to follow recommendations from weback * Update deployment.md * note that modes are not available in transition groups, fixes #1619 * add examples for in API doc * add comparison note about react-like libraries * Update components.md (#1632) * Update components.md * Update components.md * improve flow of single root component section * cookbook entry for storage (#1550) * cookbook entry for storage * minor tweak * updates to article * updates to article * maybe the last tweak * the honest to god really last mod * Update index.md (#1634) * docs(guide/comparison): correct size stat of Angular CLI project (#1638) * Update client-side-storage.md (#1640) * Update creating-custom-scroll-directives.md (#1639) * Updated broken links for the Vue Test Utils documentation. (#1643) * Reorganize component props to introduce prop types earlier, fixes #1644 (#1646) @BlitZz96 brought up a good point in [this issue](vuejs/v2.vuejs.org#1644) about users lacking the necessary background knowledge to fully understand Passing Static and Dynamic Props, at least as it relates to booleans and potentially other types in the future. To fix this, I added a new Prop Types section right before it. * First stab at SFC to npm documentation (#1558) * First stab at SFC to npm documentation * Clean up sample code, clarify .vue usage with SSR builds * Run build tasks in parallel, fix dependency order * Backtick all instances of .vue, minor edits for clarity * Fix typo on link * Update url to vue-sfc-rollup utility in acknowledgements * Fix order, other edits suggested by @sdras * Additional explanation about sfc-to-npm recipe package.json * Rename packaing-sfc-for-npm.md to packaging-sfc-for-npm.md (#1652) * Update link in comparison guide (#1653) The phrase "These state management patterns and even Redux itself can be easily integrated into Vue applications" has a link to a deprecated project. Instead I link to a yarnpkg.com search I saw used in https://vuejs.org/v2/guide/state-management.html, which links all "redux vue" projects (so it's always up to date) * translated all new content in components.md * small tweaks * typo
1 parent 2d356f1 commit 9008b29

16 files changed

+644
-54
lines changed
48.8 KB
Loading

src/images/devtools-storage-edge.png

48.1 KB
Loading

src/images/devtools-storage.png

118 KB
Loading

src/v2/api/index.md

+130-2
Original file line numberDiff line numberDiff line change
@@ -1587,14 +1587,142 @@ type: api
15871587
15881588
- 如果同时提供了事件与回调,则只移除这个回调的监听器。
15891589
1590-
### vm.$emit( event, [...args] )
1590+
### vm.$emit( eventName, [...args] )
15911591
15921592
- **参数**:
1593-
- `{string} event`
1593+
- `{string} eventName`
15941594
- `[...args]`
15951595
15961596
触发当前实例上的事件。附加参数都会传给监听器回调。
15971597
1598+
- **示例:**
1599+
1600+
只配合一个事件名使用 `$emit`
1601+
1602+
```js
1603+
Vue.component('welcome-button', {
1604+
template: `
1605+
<button v-on:click="$emit('welcome')">
1606+
Click me to be welcomed
1607+
</button>
1608+
`
1609+
})
1610+
```
1611+
1612+
```html
1613+
<div id="emit-example-simple">
1614+
<welcome-button v-on:welcome="sayHi"></welcome-button>
1615+
</div>
1616+
```
1617+
1618+
```js
1619+
new Vue({
1620+
el: '#emit-example-simple',
1621+
methods: {
1622+
sayHi: function () {
1623+
alert('Hi!')
1624+
}
1625+
}
1626+
})
1627+
```
1628+
1629+
{% raw %}
1630+
<div id="emit-example-simple" class="demo">
1631+
<welcome-button v-on:welcome="sayHi"></welcome-button>
1632+
</div>
1633+
<script>
1634+
Vue.component('welcome-button', {
1635+
template: `
1636+
<button v-on:click="$emit('welcome')">
1637+
Click me to be welcomed
1638+
</button>
1639+
`
1640+
})
1641+
new Vue({
1642+
el: '#emit-example-simple',
1643+
methods: {
1644+
sayHi: function () {
1645+
alert('Hi!')
1646+
}
1647+
}
1648+
})
1649+
</script>
1650+
{% endraw %}
1651+
1652+
配合额外的参数使用 `$emit`
1653+
1654+
```js
1655+
Vue.component('magic-eight-ball', {
1656+
data: function () {
1657+
return {
1658+
possibleAdvice: ['Yes', 'No', 'Maybe']
1659+
}
1660+
},
1661+
methods: {
1662+
giveAdvice: function () {
1663+
var randomAdviceIndex = Math.floor(Math.random() * this.possibleAdvice.length)
1664+
this.$emit('give-advice', this.possibleAdvice[randomAdviceIndex])
1665+
}
1666+
},
1667+
template: `
1668+
<button v-on:click="giveAdvice">
1669+
Click me for advice
1670+
</button>
1671+
`
1672+
})
1673+
```
1674+
1675+
```html
1676+
<div id="emit-example-argument">
1677+
<magic-eight-ball v-on:give-advice="showAdvice"></magic-eight-ball>
1678+
</div>
1679+
```
1680+
1681+
```js
1682+
new Vue({
1683+
el: '#emit-example-argument',
1684+
methods: {
1685+
showAdvice: function (advice) {
1686+
alert(advice)
1687+
}
1688+
}
1689+
})
1690+
```
1691+
1692+
{% raw %}
1693+
<div id="emit-example-argument" class="demo">
1694+
<magic-eight-ball v-on:give-advice="showAdvice"></magic-eight-ball>
1695+
</div>
1696+
<script>
1697+
Vue.component('magic-eight-ball', {
1698+
data: function () {
1699+
return {
1700+
possibleAdvice: ['Yes', 'No', 'Maybe']
1701+
}
1702+
},
1703+
methods: {
1704+
giveAdvice: function () {
1705+
var randomAdviceIndex = Math.floor(Math.random() * this.possibleAdvice.length)
1706+
this.$emit('give-advice', this.possibleAdvice[randomAdviceIndex])
1707+
}
1708+
},
1709+
template: `
1710+
<button v-on:click="giveAdvice">
1711+
Click me for advice
1712+
</button>
1713+
`
1714+
})
1715+
new Vue({
1716+
el: '#emit-example-argument',
1717+
methods: {
1718+
showAdvice: function (advice) {
1719+
alert(advice)
1720+
}
1721+
}
1722+
})
1723+
</script>
1724+
{% endraw %}
1725+
15981726
## 实例方法 / 生命周期
15991727
16001728
### vm.$mount( [elementOrSelector] )
+176
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
---
2+
title: Client-Side Storage
3+
type: cookbook
4+
order: 11
5+
---
6+
7+
## Base Example
8+
9+
Client-side storage is an excellent way to quickly add performance gains to an application. By storing data on the browser itself, you can skip fetching information from the server every time the user needs it. While especially useful when offline, even online users will benefit from using data locally versus a remote server. Client-side storage can be done with [cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies), [Local Storage](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) (technically "Web Storage"), [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API), and [WebSQL](https://www.w3.org/TR/webdatabase/) (a deprecated method that should not be used in new projects).
10+
11+
In this cookbook entry we'll focus on Local Storage, the simplest of the storage mechanisms. Local Storage uses a key/value system for storing data. It is limited to storing only simple values but complex data can be stored if you are willing to encode and decode the values with JSON. In general, Local Storage is appropriate for smaller sets of data you would want to persist, things like user preferences or form data. Larger data with more complex storage needs would be better stored typically in IndexedDB.
12+
13+
Let's begin with a simple form based example:
14+
15+
``` html
16+
<div id="app">
17+
My name is <input v-model="name">
18+
</div>
19+
```
20+
21+
This example has one form field bound to a Vue value called `name`. Here's the JavaScript:
22+
23+
``` js
24+
const app = new Vue({
25+
el:'#app',
26+
data: {
27+
name:''
28+
},
29+
mounted() {
30+
if(localStorage.name) this.name = localStorage.name;
31+
},
32+
watch: {
33+
name(newName) {
34+
localStorage.name = newName;
35+
}
36+
}
37+
});
38+
```
39+
40+
Focus on the `mounted` and `watch` parts. We use `mounted` to handle loading the value from localStorage. To handle writing the data base, we watch the `name` value and on change, immediately write it.
41+
42+
You can run this yourself here:
43+
44+
<p data-height="265" data-theme-id="0" data-slug-hash="KodaKb" data-default-tab="js,result" data-user="cfjedimaster" data-embed-version="2" data-pen-title="testing localstorage" class="codepen">See the Pen <a href="https://codepen.io/cfjedimaster/pen/KodaKb/">testing localstorage</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <a href="https://codepen.io">CodePen</a>.</p>
45+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
46+
47+
Type something in the form and then reload this page. You'll note that the value you typed previously will show up automatically. Don't forget that your browser provides excellent developer tools for inspecting client-side storage. Here's an example in Firefox:
48+
49+
![Storage devtools in Firefox](/images/devtools-storage.png)
50+
51+
And here it is in Chrome:
52+
53+
![Storage devtools in Chrome](/images/devtools-storage-chrome.png)
54+
55+
And then finally, an example in Microsoft Edge. Note that you can find application storage values under the Debugger tab.
56+
57+
![Storage devtools in Edge](/images/devtools-storage-edge.png)
58+
59+
<p class="tip">As a quick aside, these dev tools also offer you a way to remove storage values. This can be very useful when testing.</p>
60+
61+
Immediately writing the value may not advisable. Let's consider a slightly more advanced example. First, the updated form.
62+
63+
``` html
64+
<div id="app">
65+
My name is <input v-model="name">
66+
and I am <input v-model="age"> years old.
67+
<p/>
68+
<button @click="persist">Save</button>
69+
</div>
70+
```
71+
72+
Now we've got two fields (again, bound to a Vue instance) but now there is the addition of a button that runs a `persist` method. Let's look at the JavaScript.
73+
74+
``` js
75+
const app = new Vue({
76+
el:'#app',
77+
data: {
78+
name:'',
79+
age:0
80+
},
81+
mounted() {
82+
if(localStorage.name) this.name = localStorage.name;
83+
if(localStorage.age) this.age = localStorage.age;
84+
},
85+
methods: {
86+
persist() {
87+
localStorage.name = this.name;
88+
localStorage.age = this.age;
89+
console.log('now pretend I did more stuff...');
90+
}
91+
}
92+
})
93+
```
94+
95+
As before, `mounted` is used to load persisted data, if it exists. This time, though, data is only persisted when the button is clicked. We could also do any validations or transformations here before storing the value. You could also store a date representing when the values were stored. With that metadata, the `mounted` method could make a logical call on whether or not to store the values again, such as in this version below. You can try this version below.
96+
97+
<p data-height="265" data-theme-id="0" data-slug-hash="rdOjLN" data-default-tab="js,result" data-user="cfjedimaster" data-embed-version="2" data-pen-title="testing localstorage 2" class="codepen">See the Pen <a href="https://codepen.io/cfjedimaster/pen/rdOjLN/">testing localstorage 2</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <a href="https://codepen.io">CodePen</a>.</p>
98+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
99+
100+
## Working with Complex Values
101+
102+
As mentioned above, Local Storage only works with simple values. To store more complex values, like objects or arrays, you must serialize and deserialize the values with JSON. Here is a more advanced example that persists an array of cats (the best kind of array possible).
103+
104+
``` html
105+
<div id="app">
106+
<h2>Cats</h2>
107+
<div v-for="(cat,n) in cats">
108+
<p>
109+
<span class="cat">{{cat}}</span> <button @click="removeCat(n)">Remove</button>
110+
</p>
111+
</div>
112+
113+
<p>
114+
<input v-model="newCat">
115+
<button @click="addCat">Add Cat</button>
116+
</p>
117+
118+
</div>
119+
```
120+
121+
This "app" consists of a simple list on top (with a button to remove a cat) and a small form at the bottom to add a new cat. Now let's look at the JavaScript.
122+
123+
``` js
124+
const app = new Vue({
125+
el:'#app',
126+
data: {
127+
cats:[],
128+
newCat:null
129+
},
130+
mounted() {
131+
132+
if(localStorage.getItem('cats')) {
133+
try {
134+
this.cats = JSON.parse(localStorage.getItem('cats'));
135+
} catch(e) {
136+
localStorage.removeItem('cats');
137+
}
138+
}
139+
},
140+
methods: {
141+
addCat() {
142+
// ensure they actually typed something
143+
if(!this.newCat) return;
144+
this.cats.push(this.newCat);
145+
this.newCat = '';
146+
this.saveCats();
147+
},
148+
removeCat(x) {
149+
this.cats.splice(x,1);
150+
this.saveCats();
151+
},
152+
saveCats() {
153+
let parsed = JSON.stringify(this.cats);
154+
localStorage.setItem('cats', parsed);
155+
}
156+
}
157+
})
158+
```
159+
160+
In this application, we've switched to use the Local Storage APIs versus "direct" access. Both work but the API method is generally preferred. `mounted` now has to grab the value and parse the JSON value. If anything goes wrong here we assume the data is corrupt and delete it. (Remember, any time your web application uses client-side storage, the user has access to it and can modify it at will.)
161+
162+
We have three methods now to handle working with cat. Both `addCat` and `removeCat` handle updating the "live" Vue data stored in `this.cats`. They then run `saveCats` which handles serializing and persisting the data. You can play with this version below:
163+
164+
<p data-height="265" data-theme-id="0" data-slug-hash="qoYbyW" data-default-tab="js,result" data-user="cfjedimaster" data-embed-version="2" data-pen-title="localstorage, complex" class="codepen">See the Pen <a href="https://codepen.io/cfjedimaster/pen/qoYbyW/">localstorage, complex</a> by Raymond Camden (<a href="https://codepen.io/cfjedimaster">@cfjedimaster</a>) on <a href="https://codepen.io">CodePen</a>.</p>
165+
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
166+
167+
## Alternative Patterns
168+
169+
While the Local Storage API is relatively simple, it is missing some basic features that would be useful in many applications. The following plugins wrap Local Storage access and make it easier to use, while also adding functionality like default values.
170+
171+
* [vue-local-storage](https://github.com/pinguinjkeke/vue-local-storage)
172+
* [vue-reactive-storage](https://github.com/ropbla9/vue-reactive-storage)
173+
174+
## Wrapping Up
175+
176+
While the browser will never replace a server persistence system, having multiple ways to cache data locally can be a huge performance boost for your application, and working with it in Vue.js makes it even more powerful.

src/v2/cookbook/creating-custom-scroll-directives.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ new Vue({
5050

5151
我们可能还需要一个样式属性来对中间值做过渡,在这个例子中:
5252

53-
```
53+
```css
5454
.box {
5555
transition: 1.5s all cubic-bezier(0.39, 0.575, 0.565, 1);
5656
}

0 commit comments

Comments
 (0)