Vue Handbook

展开查看详情

1.

2. Table of Contents Introduction Intro to Vue Introduction to Vue Vue First App Tooling The Vue CLI DevTools Configuring VS Code for Vue Development Components Components Single File Components Templates Styling components using CSS Components building blocks Directives Events Methods Watchers Computed Properties Methods vs Watchers vs Computed Properties Props Slots Filters Communication, state management and routing Communication among components Vuex Vue Router 2

3.3

4.Introduction Introduction Thank you for getting this ebook! My name is Flavio and I run a blog at flaviocopes.com, where I write a tutorial every day. You can find me on Twitter at @flaviocopes At the end of July 2018, I will launch an online course on Vue.js with practical tutorials and direct mentorship from me. Find out more at vuecourse.com! Happy learning! 4

5.Introduction to Vue Introduction to Vue Vue is a very impressive project. It's a very popular JavaScript framework, one that's experiencing a huge growth. It is simple, tiny and very performant. Learn more about it First, what is a JavaScript frontend framework? The popularity of Vue Why developers love Vue Where does Vue.js position itself in the frameworks landscape Vue.js is an indie project Vue is a very popular JavaScript frontend framework, one that's experiencing a huge growth. It is simple, tiny (~24KB) and very performant. It feels different from all the other JavaScript frontend frameworks and view libraries. Let's find out why. First, what is a JavaScript frontend framework? If you're unsure what a JavaScript framework is, Vue is the perfect first encounter with one. A JavaScript framework helps us to create modern applications. Modern JavaScript applications are mostly used on the Web, but also power a lot of Desktop and Mobile applications. Until the early 2000s, browsers didn't have the capabilities they have now. They were a lot less powerful, and building complex applications inside them was not feasible performance- wise, and the tooling was not even something that people thought about. Everything changed when Google unveiled Google Maps and GMail, two applications that ran inside the browser. Ajax made asynchronous network requests possible, and over time developers started building on top of the Web platform, while engineers worked on the platform itself: browsers, the Web standards, the browser APIs, and the JavaScript language. Libraries like jQuery and Mootools were the first big projects that built upon JavaScript and were hugely popular for a while. They basically provided a nicer API to interact with the browser and provided workarounds for bugs and inconsistencies among the various browsers. Frameworks like Backbone, Ember, Knockout, AngularJS were the first wave of modern JavaScript frameworks. The second wave, which is the current one, has React, Angular, and Vue as its main actors. 5

6.Introduction to Vue Note that jQuery, Ember and the other projects I mentioned are still being heavily used, actively maintained, and millions of websites rely on them. That said, techniques and tools evolve, and as a JavaScript developer, you're now likely to be required to know React, Angular or Vue rather than those older frameworks. Frameworks abstract the interaction with the browser and the DOM. Instead of manipulating elements by referencing them in the DOM, we declaratively define and interact with them, at a higher level. Using a framework is like using the C programming language instead of using the Assembly language to write system programs. It's like using a computer to write a document instead of using a typewriter. It's like having a self-driving car instead of driving the car yourself. Well, not that far, but you get the idea. Instead of using low-level APIs offered by the browser to manipulate elements, and build hugely complex systems to write an application, you use tools built by very smart people that make our life easier. The popularity of Vue How much popular is Vue.js? Vue had: 7600 stars on GitHub in 2016 36700 stars on GitHub in 2017 and it has more than 100.000+ stars on GitHub, as of June 2018. Its npm download count is growing every day, and now it's at ~350.000 downloads per week. I would say Vue is a lot popular, given those numbers. In relative terms, it has approximately the same numbers of GitHub stars of React, which was born years before. Numbers are not everything, of course. The impression I have of Vue is that developers love it. A key point in time of the rise of Vue has been the adoption in the Laravel ecosystem, a hugely popular PHP web application framework, but since then it has widespread among many other development communities. Why developers love Vue First, Vue is called a progressive framework. 6

7.Introduction to Vue This means that it adapts to the needs of the developer. While other frameworks require a complete buy-in from a developer or team and often want you to rewrite an existing application because they require some specific set of conventions, Vue happily lands inside your app with a simple script tag, to start with, and it can grow along with your needs, spreading from 3 lines to managing your entire view layer. You don't need to know about webpack, Babel, npm or anything to get started with Vue, but when you're ready Vue makes it simple for you to rely on them. This is one great selling point, especially in the current ecosystem of JavaScript frontend frameworks and libraries that tends to alienate newcomers and also experienced developers that feel lost in the ocean of possibilities and choices. Vue.js is probably the more approachable frontend framework around. Some people call Vue the new jQuery, because it easily gets in the application via a script tag, and gradually gains space from there. Think of it as a compliment, since jQuery dominated the Web in the past few years, and it still does its job on a huge number of sites. Vue picks from the best ideas. It was built by picking the best ideas of frameworks like Angular, React and Knockout, and by cherry-picking the best choices those frameworks made, and excluding some less brilliant ones, it kind of started as a "best-of" set and grew from there. Where does Vue.js position itself in the frameworks landscape The 2 elephants in the room, when talking about web development, are React and Angular. How does Vue position itself relative to those 2 big and popular frameworks? Vue was created by Evan You when he was working at Google on AngularJS (Angular 1.0) apps and was born out of a need to create more performant applications. Vue picked some of the Angular templating syntax, but removed the opinionated, complex stack that Angular required, and made it very performant. The new Angular (Angular 2.0) also solved many of the AngularJS issues, but in very different ways, and requires a buy-in to TypeScript which not all developers enjoy using (or want to learn). What about React? Vue took many good ideas from React, most importantly the Virtual DOM. But Vue implements it with some sort of automatic dependency management, which tracks which components are affected by a change of the state so that only those components are re- rendered when that state property changes. In React on the other hand when a part of the state that affects a component changes, the component will be re-rendered and by default all its children will be rerendered as well. To avoid this you need to use the 7

8.Introduction to Vue shouldComponentUpdate method of each component and determine if that component should be rerendered. This gives Vue a bit of advantage in terms of ease of use, and out of the box performance gains. One big difference with React is JSX. While you can technically use JSX in Vue, it's not a popular approach and instead the templating system is used. Any HTML file is a valid Vue template, while JSX is very different than HTML and has a learning curve for people in the team that might only need to work with the HTML part of your app, like designers. Vue templates are a lot similar to Mustache and Handlebars (although they differ in terms of flexibility) and as such, they are more familiar to developers that already used frameworks like Angular and Ember. The official state management library, Vuex, follows the Flux architecture and is somewhat similar to Redux in its concepts. Again, this is part of the positive things about Vue, which saw this good pattern in React and borrowed it to its ecosystem. And while you can use Redux with Vue, Vuex is specifically tailored for Vue and its inner workings. Vue is flexible but the fact that the core team maintains two packages very important for any web app like routing and state management makes it a lot less fragmented than React for example: vue-router and vuex are key to the success of Vue. You don't need to choose or worry if that library you chose is going to be maintained in the future and will keep up with framework updates, and being official they are the canonical go-to libraries for their niche (but you can choose to use what you like, of course). One thing that puts Vue in a different bucket compared to React and Angular is that Vue is an indie project: it's not backed by a huge corporation like Facebook or Google. Instead, it's completely backed by the community, which fosters development through donations and sponsors. This makes sure the roadmap of Vue is not driven by a single company agenda. 8

9.Vue First App Vue First App If you've never created a Vue.js application, I am going to guide you through the task of creating one, and understanding how it works. The app we're going to build is already done, and it's the Vue CLI default application First example See on Codepen Second example: the Vue CLI default app Use the Vue CLI locally Use CodeSandbox The files structure index.html src/main.js src/App.vue src/components/HelloWorld.vue Run the app If you've never created a Vue.js application, I am going to guide you through the task of creating one, and understanding how it works. First example First I'll use the most basic example of using Vue. You create an HTML file which contains <html> <body> <div id="example"> <p>{{ hello }}</p> </div> <script src="https://unpkg.com/vue"></script> <script> new Vue({ el: '#example', data: { hello: 'Hello World!' } }) </script> </body> </html> 9

10.Vue First App and you open it in the browser. That's your first Vue app! The page should show a "Hello World!" message. I put the script tags at the end of the body so that they are executed in order after the DOM is loaded. What this code does is, we instantiate a new Vue app, linked to the #example element as its template (it's defined using a CSS selector usually, but you can also pass in an HTMLElement). Then, it associates that template to the data object. That is a special object that hosts the data we want Vue to render. In the template, the special {{ }} tag indicates that's some part of the template that's dynamic, and its content should be looked up in the Vue app data. See on Codepen You can see this example on Codepen: https://codepen.io/flaviocopes/pen/YLoLOp Codepen is a little different from using a plain HTML file, and you need to configure it to point to the Vue library location in the Pen settings: 10

11.Vue First App Second example: the Vue CLI default app Let's level up the game a little bit. The next app we're going to build is already done, and it's the Vue CLI default application. What is the Vue CLI? It's a command line utility that helps to speed up development by scaffolding an application skeleton for you, with a sample app in place. There are two ways you can get this application. Use the Vue CLI locally The first is to install the Vue CLI on your computer, and run the command vue create <enter the app name> 11

12.Vue First App Use CodeSandbox A simpler way, without having to install anything, is to go to https://codesandbox.io/s/vue. CodeSandbox is a cool code editor that allows you build apps in the cloud, which allows you to use any npm package and also easily integrate with Zeit Now for an easy deployment and GitHub to manage versioning. That link I put above opens the Vue CLI default application. Whether you chose to use the Vue CLI locally, or through CodeSandbox, let's inspect that Vue app in details. The files structure Beside package.json , which contains the configuration, these are the files contained in the initial project structure: index.html src/App.vue src/main.js src/assets/logo.png src/components/HelloWorld.vue index.html The index.html file is the main app file. In the body it includes just one simple element: <div id="app"></div> . This is the element the Vue application will use to attach to the DOM. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>CodeSandbox Vue</title> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> </body> </html> 12

13.Vue First App src/main.js This is the main JavaScript files that drive our app. We first import the Vue library and the App component from App.vue . We set productionTip to false, just to avoid Vue to output a "you're in development mode" tip in the console. Next, we create the Vue instance, by assigning it to the DOM element identified by #app , which we defined in index.html , and we tell it to use the App component. // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', components: { App }, template: '<App/>' }) src/App.vue App.vue is a Single File Component. It contains 3 chunks of code: HTML, CSS and JavaScript. This might seem weird at first, but Single File Components are a great way to create self- contained components that have all they need in a single file. We have the markup, the JavaScript that is going to interact with it, and style that's applied to it, which can be scoped, or not. In this case, it's not scoped, and it's just outputting that CSS which is applied like regular CSS to the page. The interesting part lies in the script tag. We import a component from the components/HelloWorld.vue file, which we'll describe later. This component is going to be referenced in our component. It's a dependency. We are going to output this code: <div id="app"> <img width="25%" src="./assets/logo.png"> <HelloWorld/> </div> 13

14.Vue First App from this component, which you see references the HelloWorld component. Vue will automatically insert that component inside this placeholder. src/components/HelloWorld.vue Here's the HelloWorld component, which is included by the App component. This component outputs a set of links, along with a message. Remember above we talked about CSS in App.vue, which was not scoped? The HelloWorld component has scoped CSS. 14

15.Vue First App You can easily determine it by looking at the style tag. If it has the scoped attribute, then it's scoped: <style scoped> This means that the generated CSS will be targeting the component uniquely, via a class that's applied by Vue transparently. You don't need to worry about this, and you know the CSS won't leak to other parts of the page. The message the component outputs is stored in the data property of the Vue instance, and outputted in the template as {{ msg }} . Anything that's stored in data is reachable directly in the template via its own name. We didn't need to say data.msg , just msg . <template> <div class="hello"> <h1>{{ msg }}</h1> <h2>Essential Links</h2> <ul> <li> <a href="https://vuejs.org" target="_blank" > Core Docs </a> </li> <li> <a href="https://forum.vuejs.org" target="_blank" > Forum </a> </li> <li> <a href="https://chat.vuejs.org" target="_blank" > Community Chat </a> </li> <li> <a href="https://twitter.com/vuejs" target="_blank" > Twitter </a> </li> <br> <li> <a 15

16.Vue First App href="http://vuejs-templates.github.io/webpack/" target="_blank" > Docs for This Template </a> </li> </ul> <h2>Ecosystem</h2> <ul> <li> <a href="http://router.vuejs.org/" target="_blank" > vue-router </a> </li> <li> <a href="http://vuex.vuejs.org/" target="_blank" > vuex </a> </li> <li> <a href="http://vue-loader.vuejs.org/" target="_blank" > vue-loader </a> </li> <li> <a href="https://github.com/vuejs/awesome-vue" target="_blank" > awesome-vue </a> </li> </ul> </div> </template> <script> export default { name: 'HelloWorld', data() { return { msg: 'Welcome to Your Vue.js App' } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> 16

17.Vue First App <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style> Run the app CodeSandbox has a cool preview functionality. You can run the app and edit anything in the source to have it immediately reflected in the preview. 17

18.Vue First App CodeSandbox is very cool for online coding and working without having to setup Vue locally. A great way to work locally is by setting up the Vue CLI. Let's find out more about it. 18

19.The Vue CLI The Vue CLI Vue is a very impressive project, and in addition to the core of the framework, it maintains a lot of utilities that make a Vue programmer's life easier. One of them is the Vue CLI. Installation What does the Vue CLI provide? How to use the CLI to create a new Vue project How to start the newly created Vue CLI application Git repository Use a preset from the command line Where presets are stored Plugins Remotely store presets Another use of the Vue CLI: rapid prototyping Webpack In the previous example I introduced an example project based on the Vue CLI. What's the Vue CLI exactly, and how it fits in the Vue ecosystem? Also, how to setup a Vue CLI-based project locally? Let's find out! Vue is a very impressive project, and in addition to the core of the framework, it maintains a lot of utilities that make a Vue programmer's life easier. One of them is the Vue CLI. CLI stands for Command Line Interface. Note: There is a huge rework of the CLI going on right now, going from version 2 to 3. While not yet stable, I will describe version 3 because it's a huge improvement over version 2, and quite different. Installation The Vue CLI is a command line utility, and you install it globally using npm: npm install -g @vue/cli or using Yarn: 19

20.The Vue CLI yarn global add @vue/cli Once you do so, you can invoke the vue command. What does the Vue CLI provide? The CLI is essential for rapid Vue.js development. Its main goal is to make sure all the tools you need are working along, to perform what you need, and abstracts away all the nitty-gritty configuration details that using each tool in isolation would require. It can perform an initial project setup and scaffolding. It's a flexible tool: once you create a project with the CLI, you can go and tweak the configuration, without having to eject your application (like you'd do with create-react-app ). When you eject from create-react-app you can update and tweak what you want, but you can't rely on the cool features that create-react-app provides You can configure anything and still be able to upgrade with ease. After you create and configure the app, it acts as a runtime dependency tool, built on top of webpack. The first encounter with the CLI is when creating a new Vue project. 20

21.The Vue CLI How to use the CLI to create a new Vue project The first thing you're going to do with the CLI is to create a Vue app: vue create example The cool thing is that it's an interactive process. You need to pick a preset. By default, there is one preset that's providing Babel and ESLint integration: I'm going to press the down arrow ⬇ and manually choose the features I want: 21

22.The Vue CLI Press space to enable one of the things you need, and then press enter to go on. Since I chose a linter/formatter, Vue CLI prompts me for the configuration. I chose ESLint + Prettier since that's my favorite setup: Next thing is choosing how to apply linting. I choose lint on save. Next up: testing. I picked testing, and Vue CLI offers me to choose between the two most popular solutions: Mocha + Chai vs Jest. 22

23.The Vue CLI Vue CLI asks me where to put all the configuration: if in the package.json file, or in dedicated configuration files, one for each tool. I chose the latter. Next, Vue CLI asks me if I want to save these presets, and allow me to pick them as a choice the next time I use Vue CLI to create a new app. It's a very convenient feature, as having a quick setup with all my preferences is a complexity reliever: 23

24.The Vue CLI Vue CLI then asks me if I prefer using Yarn or npm: and it's the last thing it asks me, and then it goes on to download the dependencies and create the Vue app: 24

25.The Vue CLI How to start the newly created Vue CLI application Vue CLI has created the app for us, and we can go in the example folder and run yarn serve to start up our first app in development mode: 25

26.The Vue CLI The starter example application source contains a few files, including package.json : 26

27.The Vue CLI This is where all the CLI commands are defined, including yarn serve , which we used a minute ago. The other commands are yarn build , to start a production build yarn lint , to run the linter yarn test:unit , to run the unit tests I will describe the sample application generated by Vue CLI in a separate tutorial. Git repository 27

28.The Vue CLI Notice the master word in the lower-left corner of VS Code? That's because Vue CLI automatically creates a repository, and makes the first commit, so we can jump right in, change things, and we know what we changed: This is pretty cool. How many times you dive in and change things, only to realize when you want to commit the result, that you didn't commit the initial state? Use a preset from the command line You can skip the interactive panel and instruct Vue CLI to use a particular preset: vue create -p favourite example-2 Where presets are stored Presets are stored in the .vuejs file in your home directory. Here's mine after creating the first "favorite" preset { "useTaobaoRegistry": false, "packageManager": "yarn", "presets": { "favourite": { "useConfigFiles": true, "plugins": { "@vue/cli-plugin-babel": {}, "@vue/cli-plugin-eslint": { "config": "prettier", "lintOn": [ "save" 28

29.The Vue CLI ] }, "@vue/cli-plugin-unit-jest": {} }, "router": true, "vuex": true } } } Plugins As you can see from reading the configuration, a preset is basically a collection of plugins, with some optional configuration. Once a project is created, you can add more plugins by using vue add : vue add @vue/cli-plugin-babel All those plugins are used in the latest version available. You can force Vue CLI to use a specific version by passing the version property: "@vue/cli-plugin-eslint": { "version": "^3.0.0" } this is useful if a new version has a breaking change or a bug, and you need to wait a little bit before using it. Remotely store presets A preset can be stored in GitHub (or on other services) by creating a repository that contains a preset.json file, which contains a single preset configuration. Extracted from the above, I made a sample preset in https://github.com/flaviocopes/vue-cli-preset/blob/master/preset.json which contains this configuration: { "useConfigFiles": true, "plugins": { "@vue/cli-plugin-babel": {}, "@vue/cli-plugin-eslint": { "config": "prettier", "lintOn": [ "save" 29