精华内容
下载资源
问答
  • Vue手册资料大全

    2019-04-17 15:36:02
    vue资料手册,由我们的马大哥亲自整理,从零开始到入门再到精通,很实用
  • vue.js手册Get this post in PDF/ePub/MOBI format at vuehandbook.com 在vuehandbook.com上以PDF / ePub / MOBI格式获取此帖子 Vue is a very popular JavaScript front-end framework, one that’s experiencing a...

    vue.js手册

    Get this post in PDF/ePub/MOBI format at vuehandbook.com

    vuehandbook.com上以PDF / ePub / MOBI格式获取此帖子

    Vue is a very popular JavaScript front-end framework, one that’s experiencing a huge amount of growth.

    Vue是一种非常流行JavaScript前端框架,正在经历巨大的增长。

    It is simple, tiny (~24KB), and very performant. It feels different from all the other JavaScript front-end frameworks and view libraries. Let’s find out why.

    它简单,小巧(〜24KB),并且性能很高。 感觉与所有其他JavaScript前端框架和视图库不同。 让我们找出原因。

    首先,什么是JavaScript前端框架? (First, what is a JavaScript front-end framework?)

    If you’re unsure what a JavaScript framework is, Vue is the perfect first encounter with one.

    如果不确定JavaScript框架是什么,Vue是一个完美的初次接触。

    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.

    JavaScript框架可帮助我们创建现代应用程序。 现代JavaScript应用程序主要在Web上使用,但也为许多桌面和移动应用程序提供支持。

    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. The tooling was not even something that people thought about.

    直到2000年代初,浏览器才具备现在所没有的功能。 它们的功能要弱得多,并且在它们内部构建复杂的应用程序在性能上是不可行的。 人们甚至都没有想到过这种工具。

    Everything changed when Google unveiled Google Maps and GMail, two applications that ran inside the browser. Ajax made asynchronous network requests possible. 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.

    当Google推出浏览器中运行的两个应用程序Google MapsGMail时 ,一切都发生了变化。 Ajax使异步网络请求成为可能。 随着时间的流逝,开发人员开始在Web平台之上进行构建,而工程师则在平台本身上进行工作-浏览器,Web标准,浏览器API和JavaScript语言。

    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.

    jQueryMootools这样的库是第一个基于JavaScript的大型项目,并在一段时间内大受欢迎。 他们基本上提供了一个更好的API与浏览器进行交互,并提供了各种浏览器之间的错误和不一致的解决方法。

    Frameworks like Backbone, Ember, Knockout, and AngularJS were the first wave of modern JavaScript frameworks.

    诸如BackboneEmberKnockoutAngularJS之类的框架是现代JavaScript框架的第一波潮流。

    The second wave, which is the current one, has React, Angular, and Vue as its main actors.

    第二波是当前波,其主要参与者是ReactAngularVue

    Note that jQuery, Ember and the other projects I mentioned are still being heavily used, actively maintained, and millions of websites rely on them.

    请注意,jQuery,Ember和我提到的其他项目仍在大量使用,积极维护和数百万个网站依赖它们。

    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.

    也就是说,技术和工具不断发展,作为JavaScript开发人员,您现在可能需要了解React,Angular或Vue,而不是那些较旧的框架。

    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.

    框架抽象了与浏览器和DOM的交互。 我们不是在DOM中通过引用元素来操作元素,而是在更高的级别上以声明方式定义它们并与之交互。

    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.

    使用框架就像使用C编程语言而不是使用汇编语言编写系统程序一样。 就像使用计算机来编写文档而不是使用打字机一样。 这就像拥有自动驾驶汽车,而不是自己驾驶汽车。

    Well, not that far, but you get the idea. Instead of using low-level APIs offered by the browser to manipulate elements, and building hugely complex systems to write an application, you use tools built by very smart people that make our life easier.

    好吧,不是很远,但是您知道了。 您不必使用由浏览器提供的低级API来操纵元素,而是使用非常聪明的人构建的工具来使我们的生活更轻松,这些工具可以构建非常复杂的系统来编写应用程序。

    Vue的受欢迎程度 (The popularity of Vue)

    How popular is Vue.js?

    Vue.js的受欢迎程度如何?

    Vue had:

    Vue有:

    • 7,600 stars on GitHub in 2016

      2016年在GitHub上获得7,600星
    • 36,700 stars on GitHub in 2017

      2017年在GitHub上有36,700星

    and it has more than 100,000+ stars on GitHub, as of June 2018.

    截至2018年6月,它在GitHub上拥有超过100,000个星星。

    Its npm download count is growing every day, and now it’s at ~350,000 downloads per week.

    它的npm下载数量每天都在增长,现在每周大约有350,000次下载。

    I would say Vue is very popular, given those numbers.

    鉴于这些数字,我会说Vue非常受欢迎。

    In relative terms, it has approximately the same numbers of GitHub stars as React, which was born years before.

    相对而言,它的GitHub星星数量与几年前诞生的React大致相同。

    Numbers are not everything, of course. The impression I have of Vue is that developers love it.

    当然,数字不是万能的。 我对Vue的印象是开发人员喜欢它。

    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 become widespread among many other development communities.

    Vue兴起的关键时刻是在Laravel生态系统中的采用,Laravel生态系统是一种非常流行PHP Web应用程序框架。 但是从那以后,它已经在许多其他开发社区中广泛传播。

    为什么开发人员喜欢Vue (Why developers love Vue)

    First, Vue is called a progressive framework.

    首先,Vue被称为渐进框架。

    This means that it adapts to the needs of the developer. 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.

    这意味着它可以适应开发人员的需求。 其他框架则需要开发人员或团队的全面支持,并且由于它们需要一些特定的约定集,因此常常希望您重写现有的应用程序。 Vue可以通过一个简单的script标签轻松地进入您的应用程序,它可以随着您的需求而增长,从3行扩展到管理整个视图层。

    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.

    您不需要了解webpackBabel ,npm或任何有关Vue入门的知识。 但是当您准备就绪时,Vue使您可以轻松依赖它们。

    This is one great selling point, especially in the current ecosystem of JavaScript front-end frameworks and libraries that tend to alienate newcomers and also experienced developers that feel lost in the ocean of possibilities and choices.

    这是一个很大的卖点,特别是在当前JavaScript前端框架和库生态系统中,这些生态系统倾向于疏远新手和经验丰富的开发人员,他们迷失在可能性和选择的海洋中。

    Vue.js is probably the most approachable front-end 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.js可能是最容易接近的前端框架。 有人称Vue为新的jQuery ,因为它很容易通过script标签进入应用程序,并从那里逐渐获得空间。 自从jQuery在过去几年中统治了Web以来,它一直是一种赞美,现在它仍然在大量站点上发挥作用。

    Vue 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 by excluding some less brilliant ones, it kind of started as a “best-of” set and grew from there.

    Vue的构建是通过选择Angular,React和Knockout等框架的最佳思想,并挑选这些框架的最佳选择来进行的。 通过排除一些不太出色的产品,它开始成为“最佳”产品,并从那里发展起来。

    Vue.js在框架环境中的什么位置? (Where does Vue.js position itself in the frameworks landscape?)

    The two elephants in the room, when talking about web development, are React and Angular. How does Vue position itself relative to those two big and popular frameworks?

    在谈论Web开发时,会议室中的两个大象是React和Angular。 Vue如何相对于这两个流行的大型框架定位自己?

    Vue was created by Evan You when he was working at Google on AngularJS (Angular 1.0) apps. It 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.

    Vue是由Evan You在Google上使用AngularJS(Angular 1.0)应用程序创建的。 它源于创建更多高性能应用程序的需要。 Vue选择了一些Angular模板语法,但删除了Angular所需的,自以为是的复杂堆栈,并使其表现出色。

    The new Angular (Angular 2.0) also solved many of the AngularJS issues, but in very different ways. It also requires a buy-in to TypeScript which not all developers enjoy using (or want to learn).

    新的Angular(Angular 2.0)也解决了许多AngularJS问题,但是方式却截然不同。 它还需要TypeScript的支持 ,并非所有开发人员都喜欢使用(或想学习)。

    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. This tracks which components are affected by a change of the state so that only those components are re-rendered when that state property changes.

    那React呢? Vue从React获得了很多好主意,最重要的是虚拟DOM。 但是Vue通过某种自动依赖管理来实现它。 这跟踪状态更改影响哪些组件,以便在状态属性更改时仅重新呈现那些组件。

    In React, on the other hand, when a part of the state that affects a component changes, the component will be re-rendered. By default all its children will be re-rendered as well. To avoid this you need to use the shouldComponentUpdate method of each component and determine if that component should be re-rendered. This gives Vue a bit of an advantage in terms of ease of use, and out of the box performance gains.

    另一方面,在React中,当影响组件的状态的一部分发生变化时,组件将被重新渲染。 默认情况下,其所有子级也会重新渲染。 为了避免这种情况,您需要使用每个组件的shouldComponentUpdate方法,并确定是否应重新呈现该组件。 就易用性和开箱即用的性能而言,这给Vue带来了一些优势。

    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. JSX is very different than HTML, and has a learning curve for people on the team that might only need to work with the HTML part of the app, like designers.

    与React的一大不同是JSX 。 尽管您可以在Vue中使用JSX,但它并不是一种流行的方法,而是使用了模板系统 。 任何HTML文件都是有效的Vue模板。 JSX与HTML截然不同,它为团队中的人员提供了学习曲线,他们可能只需要使用应用程序HTML部分,例如设计师。

    Vue templates are very similar to Mustache and Handlebars (although they differ in terms of flexibility). As such, they are more familiar to developers that already used frameworks like Angular and Ember.

    Vue模板与MoustacheHandlebars非常相似(尽管它们在灵活性方面有所不同)。 因此,对于已经使用Angular和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 for its ecosystem. And while you can use Redux with Vue, Vuex is specifically tailored for Vue and its inner workings.

    官方状态管理库Vuex遵循Flux架构,其概念在某种程度上类似于Redux 。 再次,这是关于Vue的积极事情的一部分,Vue在React中看到了这种良好模式,并将其借用于其生态系统。 尽管可以将Redux与Vue结合使用,但Vuex是专门针对Vue及其内部功能而量身定制的。

    Vue is flexible, but the fact that the core team maintains two packages that are 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.

    Vue非常灵活,但是核心团队维护着两个软件包,这对于任何Web应用程序(如路由和状态管理)都非常重要,这使得它比React更加零碎。 例如: vue-routervuex是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. Since they are 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.

    与React和Angular相比,使Vue处于不同的类别的一件事是Vue是一个独立项目:它没有像Facebook或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’s agenda.

    相反,它得到了社区的完全支持,该社区通过捐赠和赞助者促进发展。 这可以确保Vue的路线图不受单个公司议程的驱动。

    您的第一个Vue应用 (Your first Vue App)

    If you’ve never created a Vue.js application, I am going to guide you through the task of creating one so that you understand how it works.

    如果您从未创建过Vue.js应用程序,那么我将指导您完成创建应用程序的任务,以便您了解其工作方式。

    第一个例子 (First example)

    First I’ll go through the most basic example of using Vue.

    首先,我将介绍使用Vue的最基本示例。

    You create an HTML file which contains:

    您创建一个HTML文件,其中包含:

    <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>

    and you open it in the browser. That’s your first Vue app! The page should show a “Hello World!” message.

    然后在浏览器中将其打开。 这是您的第一个Vue应用! 该页面应显示“ Hello World!” 信息。

    I put the script tags at the end of the body so that they are executed in order after the DOM is loaded.

    我将脚本标签放在正文的末尾,以便在加载DOM之后按顺序执行它们。

    What this code does is 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.

    该代码的作用是实例化一个新的Vue应用程序,该应用程序链接到#example元素作为其模板。 通常是使用CSS选择器定义的,但是您也可以传入HTMLElement

    Then, it associates that template to the data object. That is a special object that hosts the data we want Vue to render.

    然后,它将该模板与data对象相关联。 这是一个特殊的对象,用于承载我们要Vue渲染的数据。

    In the template, the special {{ }} tag indicates that this is some part of the template that's dynamic, and its content should be looked up in the Vue app data.

    在模板中,特殊的{{ }}标签表示这是动态模板的一部分,应在Vue应用程序数据中查找其内容。

    You can see this example on CodePen.

    您可以在CodePen上看到此示例。

    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:

    CodePen与使用纯HTML文件略有不同,您需要对其进行配置以指向Pen设置中的Vue库位置:

    第二个示例:Vue CLI默认应用 (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.

    让我们稍微升级一下游戏。 我们将要构建的下一个应用程序已经完成,它是Vue CLI的默认应用程序。

    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.

    什么是Vue CLI? 它是一个命令行实用程序,可通过在适当位置安装示例应用程序来为您架设一个应用程序框架来帮助加快开发速度。

    There are two ways you can get this application:

    有两种方法可以获取此应用程序:

    Use the Vue CLI locally

    在本地使用Vue CLI

    The first is to install the Vue CLI on your computer and run the command:

    首先是在计算机上安装Vue CLI并运行以下命令:

    vue create <enter the app name>

    Use CodeSandbox

    使用CodeSandbox

    A simpler way, without having to install anything, is to go to CodeSandbox. The link opens the Vue CLI default application.

    一个简单的方法(无需安装任何程序)是转到CodeSandbox 。 该链接将打开Vue CLI默认应用程序。

    CodeSandbox is a cool code editor that allows you build apps in the cloud. You can use any npm package, and can easily integrate with Zeit Now for an easy deployment and with GitHub to manage versioning.

    CodeSandbox是一个很棒的代码编辑器,可让您在云中构建应用程序。 您可以使用任何npm软件包,并且可以轻松地与Zeit Now集成以实现轻松部署,并可以与GitHub集成以管理版本控制。

    Whether you chose to use the Vue CLI locally, or go through CodeSandbox, let’s inspect that Vue app in detail.

    无论您是选择在本地使用Vue CLI,还是通过CodeSandbox,我们都将详细检查该Vue应用程序。

    文件结构 (The files structure)

    Beside package.json, which contains the configuration, these are the files contained in the initial project structure:

    package.json (其中包含配置)旁边,这些是初始项目结构中包含的文件:

    • index.html

      index.html

    • src/App.vue

      src/App.vue

    • src/main.js

      src/main.js

    • src/assets/logo.png

      src/assets/logo.png

    • src/components/HelloWorld.vue

      src/components/HelloWorld.vue

    index.html (index.html)

    The index.html file is the main app file.

    index.html文件是主应用程序文件。

    In the body it includes just one simple element: <div id="app"></div>. This is the element the Vue application we’ll use to attach to the DOM.

    在主体中,它仅包含一个简单元素: <div id="app"> </ div>。 这是我们将用于附加到DOM的Vue应用程序的元素。

    <!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>

    src/main.js (src/main.js)

    This is the main JavaScript file that drives our app.

    这是驱动我们的应用程序的主要JavaScript文件。

    We first import the Vue library and the App component from App.vue.

    我们首先从App.vue导入Vue库和App组件。

    We set productionTip to false, to avoid Vue outputting a “you’re in development mode” tip in the console.

    我们将productionTip设置为false ,以避免Vue在控制台中输出“您处于开发模式”提示。

    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.

    接下来,我们通过将Vue实例分配给我们在index.html定义的#app标识的DOM元素来创建Vue实例,并告诉它使用App组件。

    // 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 (src/App.vue)

    App.vue is a Single File Component. It contains three chunks of code: HTML, CSS, and JavaScript.

    App.vue是单个文件组件。 它包含三个代码块:HTML,CSS和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.

    我们具有标记,将要与之交互JavaScript以及应用于其的样式,可以对其范围进行限制。 在这种情况下,它没有作用域,只是输出了像常规CSS一样应用到页面CSS。

    The interesting part lies in the script tag.

    有趣的部分在于script标签。

    We import a component from the components/HelloWorld.vue file, which we'll describe later.

    我们从components/HelloWorld.vue文件导入一个组件,稍后将对其进行描述。

    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>

    from this component, which you see references the HelloWorld component. Vue will automatically insert that component inside this placeholder.

    在该组件中,您会看到它引用了HelloWorld组件。 Vue会自动将该组件插入此占位符。

    <template>
      <div id="app">
        <img width="25%" src="./assets/logo.png">
        <HelloWorld/>
      </div>
    </template>
    
    <script>
    import HelloWorld from './components/HelloWorld'
    
    export default {
      name: 'App',
      components: {
        HelloWorld
      }
    }
    </script>
    
    <style>
    #app {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>

    src/components/HelloWorld.vue (src/components/HelloWorld.vue)

    Here’s the HelloWorld component, which is included by the App component.

    这是HelloWorld组件,它包含在App组件中。

    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.

    还记得上面我们讨论过App.vue中CSS,但没有限定范围吗? HelloWorld组件的作用域为CSS。

    You can easily determine it by looking at the style tag. If it has the scoped attribute, then it's scoped: <style scoped>

    您可以通过查看style标签轻松确定它。 如果它具有scoped属性,则它的范围是: <style scop ed>

    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.

    这意味着生成CSS将通过Vue透明应用的类来唯一地定位组件。 您无需为此担心,并且知道CSS不会泄漏到页面的其他部分。

    The message the component outputs is stored in the data property of the Vue instance, and outputted in the template as {{ msg }}.

    组件输出的消息存储在Vue实例的data属性中,并在模板中以{{ 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.

    data存储的任何内容都可以通过自己的名称直接在模板中访问。 我们不需要说data.msg ,只需要说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
              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 -->
    <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.

    CodeSandbox具有很酷的预览功能。 您可以运行该应用程序并编辑源代码中的任何内容,以使其立即反映在预览中。

    Vue CLI (The Vue CLI)

    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 (command line interface). Let’s find out more about it.

    CodeSandbox非常适合在线编码和工作,而无需在本地设置Vue。 在本地工作的好方法是设置Vue CLI(命令行界面)。 让我们进一步了解它。

    In the previous example, I introduced an example project based on the Vue CLI. What’s the Vue CLI exactly, and how does it fit in the Vue ecosystem? Also, how do we setup a Vue CLI-based project locally? Let’s find out!

    在上一个示例中,我介绍了一个基于Vue CLI的示例项目。 Vue CLI到底是什么,它如何适合Vue生态系统? 另外,我们如何在本地设置基于Vue CLI的项目? 让我们找出答案!

    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.

    注意:从版本2到版本3,现在正在对CLI进行大量修改。虽然尚不稳定,但我将介绍版本3,因为它是对版本2的巨大改进,并且有很大的不同。

    安装 (Installation)

    The Vue CLI is a command line utility, and you install it globally using npm:

    Vue CLI是一个命令行实用程序,您可以使用npm在全局安装它:

    npm install -g @vue/cli

    or using Yarn:

    或使用纱线:

    yarn global add @vue/cli

    Once you do so, you can invoke the vue command.

    完成后,您可以调用vue命令。

    Vue CLI提供了什么? (What does the Vue CLI provide?)

    The CLI is essential for rapid Vue.js development.

    CLI对于快速Vue.js开发至关重要。

    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).

    这是一个灵活的工具。 使用CLI创建项目后,就可以进行配置调整,而不必退出应用程序(就像对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.

    create-react-app弹出时,可以更新和调整所需内容,但不能依赖create-react-app提供的出色功能。

    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.

    创建和配置应用程序后,它充当基于Webpack的运行时依赖工具。

    The first encounter with the CLI is when creating a new Vue project.

    与CLI的第一次接触是在创建新的Vue项目时。

    如何使用CLI创建新的Vue项目 (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:

    使用CLI要做的第一件事是创建一个Vue应用程序:

    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 provides Babel and ESLint integration:

    最酷的是,这是一个交互式过程。 您需要选择一个预设。 默认情况下,有一个预设可提供Babel和ESLint集成:

    I’m going to press the down arrow ⬇️ and manually choose the features I want:

    我将按向下箭头⬇️并手动选择所需的功能:

    Press space to enable one of the things you need, and then press enter to go on. Since I chose Linter / Formatter, Vue CLI prompts me for the configuration. I chose ESLint + Prettier since that's my favorite setup:

    space键启用所需的功能之一,然后按enter键继续。 由于我选择了Linter / Formatter ,因此Vue CLI会提示我进行配置。 我选择了ESLint + Prettier因为这是我最喜欢的设置:

    Next thing is choosing how to apply linting. I choose Lint on save.

    下一步是选择如何应用棉绒。 我选择Lint on save

    Next up: testing. Vue CLI lets me choose between the two most popular unit testing solutions: Mocha + Chai and Jest.

    接下来:测试。 Vue CLI让我在两种最受欢迎​​的单元测试解决方案之间进行选择: Mocha + ChaiJest

    Vue CLI asks me where to put all the configuration: in the package.json file, or in dedicated configuration files, one for each tool. I chose the latter.

    Vue CLI询问我将所有配置放在哪里:在package.json文件或专用配置文件中,每个工具一个。 我选择了后者。

    Next, Vue CLI asks me if I want to save these presets, and allows 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:

    接下来,Vue CLI询问我是否要保存这些预设,并允许我下次使用Vue CLI创建新应用时选择它们。 这是一个非常方便的功能,因为根据我的喜好进行快速设置可以缓解复杂性:

    Vue CLI then asks me if I prefer using Yarn or NPM:

    然后,Vue CLI询问我是否更喜欢使用Yarn或NPM:

    This is the last thing it asks me, and then it goes on to download the dependencies and create the Vue app:

    这是它问我的最后一件事,然后继续下载依赖项并创建Vue应用程序:

    如何启动新创建的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:

    Vue CLI已经为我们创建了应用程序,我们可以进入example文件夹并运行yarn serve以在开发模式下启动我们的第一个应用程序:

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

    入门示例应用程序源代码包含一些文件,包括package.json

    This is where all the CLI commands are defined, including yarn serve, which we used a minute ago. The other commands are

    这是定义所有CLI命令的地方,包括我们在一分钟前使用的yarn serve 。 其他命令是

    • yarn build, to start a production build

      yarn build ,开始生产

    • yarn lint, to run the linter

      yarn lint

    • yarn test:unit, to run the unit tests

      yarn test:unit ,运行单元测试

    I will describe the sample application generated by Vue CLI in a separate tutorial.

    我将在单独的教程中描述由Vue CLI生成的示例应用程序。

    Git仓库 (Git repository)

    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:

    注意VS Code左下角的master词吗? 这是因为Vue CLI自动创建存储库并进行第一次提交。 这样我们就可以跳进去,进行更改,然后我们知道更改了什么:

    This is pretty cool. How many times do 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 CLI使用特定的预设:

    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:

    预设存储在主目录中的.vuejs文件中。 创建第一个“收藏夹”预设后,这是我的:

    {
      "useTaobaoRegistry": false,
      "packageManager": "yarn",
      "presets": {
        "favourite": {
          "useConfigFiles": true,
          "plugins": {
            "@vue/cli-plugin-babel": {},
            "@vue/cli-plugin-eslint": {
              "config": "prettier",
              "lintOn": [
                "save"
              ]
            },
            "@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 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:

    所有这些插件均以可用的最新版本使用。 您可以通过传递version属性来强制Vue CLI使用特定版本:

    "@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.

    通过创建一个包含一个preset.json文件的存储库,可以将一个预置存储在GitHub(或其他服务)中,该文件包含一个预置配置。

    Extracted from the above, I made a sample preset which contains this configuration:

    从以上摘录中,我制作了一个包含以下配置的示例预设

    {  "useConfigFiles": true,  "plugins": {    "@vue/cli-plugin-babel": {},    "@vue/cli-plugin-eslint": {      "config": "prettier",      "lintOn": [        "save"      ]    },    "@vue/cli-plugin-unit-jest": {}  },  "router": true,  "vuex": true}

    It can be used to bootstrap a new application using:

    可以使用以下命令来引导新应用程序:

    vue create --preset flaviocopes/vue-cli-preset example3

    Vue CLI的另一种用法:快速原型制作 (Another use of the Vue CLI: rapid prototyping)

    Up until now, I’ve explained how to use the Vue CLI to create a new project from scratch, with all the bells and whistles. But for really quick prototyping, you can create a really simple Vue application (even one that’s self-contained in a single .vue file) and serve that, without having to download all the dependencies in the node_modules folder.

    到目前为止,我已经解释了如何使用Vue CLI从头开始创建所有项目。 但是对于真正快速的原型制作,您可以创建一个非常简单的Vue应用程序(甚至是一个包含在单个.vue文件中的应用程序)并提供该服务,而不必下载node_modules文件夹中的所有依赖node_modules

    How? First install the cli-service-global global package:

    怎么样? 首先安装cli-service-global全局软件包:

    npm install -g @vue/cli-service-global
    //or
    yarn global add @vue/cli-service-global

    Create an app.vue file:

    创建一个app.vue文件:

    <template>    <div>        <h2>Hello world!</h2>        <marquee>Heyyy</marquee>    </div></template>

    and then run

    然后运行

    vue serve app.vue

    You can serve more organized projects, composed by JavaScript and HTML files as well. Vue CLI by default uses main.js / index.js as its entry point, and you can have a package.json and any tool configuration set up. vue serve will pick it up.

    您还可以提供由JavaScript和HTML文件组成的更有条理的项目。 默认情况下,Vue CLI使用main.js / index.js作为其入口点,并且您可以设置package.json和任何工具配置。 vue serve会捡起来。

    Since this uses global dependencies, it’s not an optimal approach for anything more than a demonstration or quick testing.

    由于这使用了全局依赖性,因此除了演示或快速测试之外,它不是最佳方法。

    Running vue build will prepare the project for deployment in dist/, and will generate all the corresponding code (also for vendor dependencies).

    运行vue build将为要在dist/部署的项目做好准备,并将生成所有相应的代码(也用于供应商依赖性)。

    Webpack (Webpack)

    Internally, Vue CLI uses Webpack, but the configuration is abstracted and we don’t even see the config file in our folder. You can still have access to it by calling vue inspect:

    在内部,Vue CLI使用Webpack,但是配置是抽象的,我们甚至在文件夹中都看不到配置文件。 您仍然可以通过调用vue inspect来访问它:

    Vue开发工具 (The Vue DevTools)

    When you’re first experimenting with Vue, if you open the Browser Developer Tools, you will find this message: “Download the Vue Devtools extension for a better development experience: https://github.com/vuejs/vue-devtools"

    首次尝试使用Vue时,如果打开浏览器开发人员工具,则会发现以下消息:“下载Vue Devtools扩展以获得更好的开发体验: https : //github.com/vuejs/vue-devtools

    This is a friendly reminder to install the Vue Devtools Extension. What’s that? Any popular framework has its own devtools extension, which generally adds a new panel to the browser developer tools that is much more specialized than the ones that the browser ships by default. In this case, the panel will let us inspect our Vue application and interact with it.

    这是一个友好的提醒,请安装Vue Devtools Extension。 那是什么? 任何流行的框架都有其自己的devtools扩展,通常会向浏览器开发人员工具添加一个新面板,该面板比浏览器默认提供的工具更加专业。 在这种情况下,面板将使我们检查Vue应用程序并与其进行交互。

    This tool will be an amazing help when building Vue apps. The developer tools can only inspect a Vue application when it’s in development mode. This makes sure no one can use them to interact with your production app — and will make Vue more performant, because it does not have to care about the Dev Tools.

    构建Vue应用程序时,此工具将为您提供惊人的帮助。 开发人员工具只能在处于开发模式时检查Vue应用程序。 这样可以确保没有人可以使用它们与您的生产应用程序进行交互,并且可以使Vue的性能更高,因为它不必关心开发工具。

    Let’s install it!

    让我们安装它!

    There are 3 ways to install the Vue Dev Tools:

    有3种安装Vue Dev Tools的方法:

    • on Chrome

      在Chrome上
    • on Firefox

      在Firefox上
    • as a standalone application

      作为独立的应用程序

    Safari, Edge and other browsers are not supported with a custom extension, but using the standalone application you can debug a Vue.js app running in any browser.

    自定义扩展不支持Safari,Edge和其他浏览器,但是使用独立应用程序,您可以调试在任何浏览器中运行的Vue.js应用程序。

    在Chrome上安装 (Install on Chrome)

    Go to this page on the Google Chrome Store and click Add to Chrome.

    转到Google Chrome 商店上的此页面,然后点击Add to Chrome

    Go through the installation process:

    完成安装过程:

    The Vue.js devtools icon shows up in the toolbar. If the page does not have a Vue.js instance running, it’s grayed out.

    Vue.js devtools图标显示在工具栏中。 如果页面没有正在运行的Vue.js实例,则该页面显示为灰色。

    If Vue.js is detected, the icon has the Vue logo’s colors.

    如果检测到Vue.js,则该图标具有Vue徽标的颜色。

    The icon does nothing except show us that there is a Vue.js instance. To use the devtools, we must open the Developer Tools panel, using “View → Developer → Developer Tools”, or Cmd-Alt-i

    图标什么也不做只是告诉我们, 一个Vue.js实例。 要使用devtools,我们必须使用“视图→开发人员→开发人员工具”或Cmd-Alt-i打开“开发人员工具”面板

    在Firefox上安装 (Install on Firefox)

    You can find the Firefox dev tools extension in the Mozilla Add-ons store.

    您可以在Mozilla附加组件商店中找到Firefox开发工具扩展。

    Click “Add to Firefox” and the extension will be installed. As with Chrome, a grayed icon shows up in the toolbar

    单击“添加到Firefox”,将安装扩展名。 与Chrome一样,工具栏中会显示灰色图标

    And when you visit a site that has a Vue instance running, it will become green, and when we open the Dev Tools we will see a “Vue” panel:

    当您访问正在运行Vue实例的站点时,该站点将变为绿色,并且当我们打开开发工具时,我们将看到一个“ Vue”面板:

    安装独立应用 (Install the standalone app)

    Alternatively, you can use the DevTools standalone app.

    或者,您可以使用DevTools独立应用程序。

    Simply install it using:

    只需使用以下命令安装它:

    npm install -g @vue/devtools
    //or
    yarn global add @vue/devtools

    and run it by calling:

    并通过调用来运行它:

    vue-devtools

    This will open the standalone Electron-based application.

    这将打开独立的基于电子的应用程序。

    Now, paste the script tag it shows you

    现在,粘贴显示给您的脚本标签

    <script src="http://localhost:8098"></script>

    inside the project index.html file, and wait for the app to be reloaded. It will automatically connect to the app.

    在项目index.html文件中,然后等待应用程序重新加载。 它将自动连接到应用程序。

    如何使用开发人员工具 (How to use the Developer Tools)

    As mentioned, the Vue DevTools can be activated by opening the Developer Tools in the browser and moving to the Vue panel.

    如前所述,可以通过在浏览器中打开开发人员工具并移至Vue面板来激活Vue DevTools。

    Another option is to right-click on any element in the page, and choose “Inspect Vue component”:

    另一个选项是右键单击页面中的任何元素,然后选择“检查Vue组件”:

    When the Vue DevTools panel is open, we can navigate the components tree. When we choose a component from the list on the left, the right panel shows the props and data it holds:

    打开Vue DevTools面板后,我们可以导航组件树。 当我们从左侧的列表中选择一个组件时,右侧面板将显示其拥有的道具和数据:

    On the top there are fourbuttons:

    在顶部有四个按钮:

    • Components (the current panel), which lists all the component instances running in the current page. Vue can have multiple instances running at the same time. For example, it might manage your shopping cart widget and the slideshow, with separate, lightweight apps.

      组件 (当前面板),其中列出了当前页面中运行的所有组件实例。 Vue可以同时运行多个实例。 例如,它可以使用单独的轻型应用程序管理购物车小部件和幻灯片。

    • Vuex is where you can inspect the state managed through Vuex.

      在Vuex中,您可以检查通过Vuex管理的状态。

    • Events shows all the events emitted.

      事件显示所有发出的事件。

    • Refresh reloads the devtools panel.

      刷新将重新加载devtools面板。

    Notice the small = $vm0 text beside a component? It's a handy way to inspect a component using the Console. Pressing the "esc" key shows up the console in the bottom of the devtools, and you can type $vm0 to access the Vue component:

    注意组件旁边的小= $vm0文本吗? 这是使用控制台检查组件的便捷方法。 按下“ esc”键将在devtools底部显示控制台,您可以键入$vm0来访问Vue组件:

    It’s very cool to inspect and interact with components without having to assign them to a global variable in the code.

    检查组件并与之交互非常酷,而不必在代码中将它们分配给全局变量。

    过滤组件 (Filter components)

    Start typing a component name, and the components tree will filter out the ones that don’t match.

    开始输入组件名称,组件树将过滤出不匹配的组件。

    在页面中选择一个组件 (Select a component in the page)

    Click the Select component in the page button.

    单击Select component in the page按钮中的Select component in the page

    You can hover over any component in the page with the mouse, click it, and it will be opened in the devtools.

    您可以用鼠标悬停在页面上的任何组件上,单击它,然后它将在devtools中打开。

    格式化组件名称 (Format components names)

    You can choose to show components in camelCase or use dashes.

    您可以选择在camelCase中显示组件或使用破折号。

    筛选检查的数据 (Filter inspected data)

    On the right panel, you can type any word to filter the properties that don’t match it.

    在右侧面板上,您可以输入任何单词以过滤不匹配的属性。

    检查DOM (Inspect DOM)

    Click the Inspect DOM button to be brought to the DevTools Elements inspector, with the DOM element generated by the component:

    单击“检查DOM”按钮,将其带到DevTools Elements检查器中,该DOM元素由组件生成:

    在编辑器中打开 (Open in editor)

    Any user component (not framework-level components) has a button that opens it in your default editor. Very handy.

    任何用户组件(不是框架级组件)都有一个按钮,可以在默认编辑器中将其打开。 非常便利。

    设置VS Code以与Vue一起使用 (Setup VS Code to work with Vue)

    Visual Studio Code is one of the most used code editors in the world right now. Editors have, like many software products, a cycle. Once TextMate was the favorite among developers, then it was Sublime Text, now it’s VS Code.

    Visual Studio Code是目前世界上最常用的代码编辑器之一。 像许多软件产品一样,编辑器有一个循环。 一旦TextMate成为开发人员的最爱,那么它就是Sublime Text ,现在是VS Code。

    The cool thing about being popular is that people dedicate a lot of time to building plugins for everything they can imagine.

    受欢迎的有趣之处在于,人们花了很多时间来为他们可以想象的一切构建插件。

    One such plugin is an awesome tool that can help us Vue.js developers.

    一个这样的插件是一个很棒的工具,可以帮助我们Vue.js开发人员。

    威图 (Vetur)

    It’s called Vetur, it’s hugely popular (more than 3 million downloads), and you can find it on the Visual Studio Marketplace.

    它被称为Vetur,非常受欢迎(下载量超过300万),您可以在Visual Studio Marketplace上找到它。

    安装Vetur (Installing Vetur)

    Clicking the Install button will trigger the installation panel in VS Code:

    单击“安装”按钮将在VS Code中触发安装面板:

    You can also simply open the Extensions in VS Code and search for “vetur”:

    您也可以简单地在VS Code中打开扩展,然后搜索“ vetur”:

    What does this extension provide?

    此扩展程序提供什么?

    语法高亮 (Syntax highlighting)

    Vetur provides syntax highlighting for all your Vue source code files.

    Vetur为所有Vue源代码文件提供语法高亮显示。

    Without Vetur, a .vue file will be displayed in this way by VS Code:

    如果没有Vetur,VS代码将以这种方式显示.vue文件:

    with Vetur installed:

    安装了Vetur时:

    VS Code is able to recognize the type of code contained in a file from its extension.

    VS Code能够从其扩展名识别文件中包含的代码类型。

    Using Single File Components, you can mix different types of code inside the same file, from CSS to JavaScript to HTML.

    使用单个文件组件,您可以在同一文件中混合使用不同类型的代码,从CSS到JavaScript到HTML。

    VS Code by default cannot recognize this kind of situation, and Vetur provides syntax highlighting for each kind of code you use.

    默认情况下,VS Code无法识别这种情况,而Vetur为您使用的每种代码提供语法高亮显示。

    Vetur enables support, among other things, for:

    Vetur支持以下方面的支持:

    • HTML

      HTML
    • CSS

      CSS
    • JavaScript

      JavaScript
    • Pug

      哈巴狗
    • Haml

      哈姆
    • SCSS

      SCSS
    • PostCSS

      PostCSS
    • Sass

      萨斯
    • Stylus

      触控笔
    • TypeScript

      打字稿

    片段 (Snippets)

    As with syntax highlighting, since VS Code cannot determine the kind of code contained in a part of a .vue file, it cannot provide the snippets we all love. Snippets are pieces of code we can add to the file, provided by specialized plugins.

    与语法突出显示一样,由于VS Code无法确定.vue文件的一部分中包含的代码类型,因此它无法提供我们都喜欢的代码段。 代码片段是我们可以添加到文件中的代码片段,由专用插件提供。

    Vetur gives VS Code the ability to use your favorite snippets in Single File Components.

    Vetur使VS Code能够在单个文件组件中使用您喜欢的代码段。

    智能感知 (IntelliSense)

    IntelliSense is also enabled by Vetur, for each different language, with autocomplete:

    Vetur还为每种不同的语言启用了IntelliSense ,并具有自动完成功能:

    脚手架 (Scaffolding)

    In addition to enabling custom snippets, Vetur provides its own set of snippets. Each one creates a specific tag (template, script, or style) with its own language:

    除了启用自定义片段外,Vetur还提供了自己的片段集。 每个人都使用自己的语言创建一个特定的标签(模板,脚本或样式):

    • scaffold

      scaffold

    • template with html

      template with html

    • template with pug

      template with pug

    • script with JavaScript

      script with JavaScript

    • script with TypeScript

      script with TypeScript

    • style with CSS

      style with CSS

    • style with CSS (scoped)

      style with CSS (scoped)

    • style with scss

      style with scss

    • style with scss (scoped)

      style with scss (scoped)

    • style with less

      style with less

    • style with less (scoped)

      style with less (scoped)

    • style with sass

      style with sass

    • style with sass (scoped)

      style with sass (scoped)

    • style with postcss

      style with postcss

    • style with postcss (scoped)

      style with postcss (scoped)

    • style with stylus

      style with stylus

    • style with stylus (scoped)

      style with stylus (scoped)

    If you type scaffold, you'll get a starter pack for a single-file component:

    如果输入scaffold ,您将获得一个单文件组件的入门包:

    <template>
    </template>
    <script>export default {
    }</script>
    <style>
    </style>

    The others are specific and create a single block of code.

    其他的则是特定的,并创建单个代码块。

    Note: (scoped) in the above list means that it applies to the current component only.

    注意:以上列表中的(作用域)意味着它仅适用于当前组件。

    Emmet (Emmet)

    Emmet, the popular HTML/CSS abbreviations engine, is supported by default. You can type one of the Emmet abbreviations, and by pressing tab VS Code will automatically expand it to the HTML equivalent:

    默认情况下, Emmet是流行HTML / CSS缩写引擎。 您可以输入Emmet缩写之一,然后按VS Code tab将其自动扩展为等效HTML:

    整理和错误检查 (Linting and error checking)

    Vetur integrates with ESLint through the VS Code ESLint plugin.

    Vetur通过VS Code ESLint插件与ESLint集成。

    代码格式化 (Code Formatting)

    Vetur provides automatic support for code formatting to format the whole file upon save — in combination with the "editor.formatOnSave" VS Code setting.

    Vetur为代码格式化提供自动支持,以在保存时对整个文件进行格式化-结合"editor.formatOnSave" VS Code设置。

    You can choose to disable automatic formatting for some specific languages by setting the vetur.format.defaultFormatter.XXXXX to none in the VS Code settings. To change one of those settings, just start searching for the string, and override what you want in the user settings on the right panel.

    您可以通过在VS Code设置vetur.format.defaultFormatter.XXXXX设置为none来选择禁用某些特定语言的自动格式设置。 要更改这些设置之一,只需开始搜索字符串,然后在右侧面板的用户设置中覆盖所需的内容即可。

    Most of the languages supported use Prettier for automatic formatting, a tool that’s becoming an industry standard. It uses your Prettier configuration to determine your preferences.

    支持的大多数语言都使用Prettier进行自动格式化,该工具已成为行业标准。 它使用您的Prettier配置来确定您的首选项。

    介绍Vue组件 (Introducing Vue Components)

    Components are single, independent units of an interface. They can have their own state, markup, and style.

    组件是接口的单个​​独立单元。 他们可以具有自己的状态,标记和样式。

    如何使用组件 (How to use components)

    Vue components can be defined in four main ways. Let’s talk in code.

    Vue组件可以通过四种主要方式进行定义。 让我们谈谈代码。

    The first is:

    第一个是:

    new Vue({  /* options */})

    The second is:

    第二个是:

    Vue.component('component-name', {  /* options */})

    The third is by using local components. These are components that are only accessible by a specific component, and not available elsewhere (great for encapsulation).

    第三是通过使用本地组件。 这些是只能由特定组件访问的组件,而在其他地方则不可用(非常适合封装)。

    The fourth is in .vue files, also called Single File Components.

    第四个位于.vue文件中,也称为“单个文件组件”。

    Let’s dive into the first 3 ways in detail.

    让我们详细介绍前三种方式。

    Using new Vue() or Vue.component() is the standard way to use Vue when you're building an application that is not a Single Page Application (SPA). You use this method, rather, when you’re just using Vue.js in some pages, like in a contact form or in the shopping cart. Or maybe Vue is used in all pages, but the server is rendering the layout, and you serve the HTML to the client, which then loads the Vue application you build.

    在构建不是单页应用程序(SPA)的应用程序时,使用new Vue()Vue.component()是使用Vue的标准方法。 相反,当您仅在某些页面中使用Vue.js(例如在联系表单或购物车中)时,就使用此方法。 也许在所有页面中都使用了Vue,但是服务器正在渲染布局,然后您将HTML提供给客户端,然后客户端将加载您构建的Vue应用程序。

    In an SPA, where it’s Vue that builds the HTML, it’s more common to use Single File Components as they are more convenient.

    在SPA中,是由Vue构建HTML的,使用单文件组件更为方便,因此更为常见。

    You instantiate Vue by mounting it on a DOM element. If you have a <div id="app"></div> tag, you will use:

    您可以通过将Vue安装在DOM元素上来实例化Vue。 如果您有<div id="app"> </ div>标记,则将使用:

    new Vue({ el: '#app' })

    A component initialized with new Vue has no corresponding tag name, so it's usually the main container component.

    new Vue初始化的组件没有相应的标签名称,因此通常是主要的容器组件。

    Other components used in the application are initialized using Vue.component(). Such a component allows you to define a tag — with which you can embed the component multiple times in the application — and specify the output of the component in the template property:

    使用Vue.component()初始化应用程序中使用的其他组件。 这样的组件允许您定义一个标记(您可以使用该标记在应用程序中多次嵌入该组件),并在template属性中指定该组件的输出:

    <div id="app">  <user-name name="Flavio"></user-name></div>
    Vue.component('user-name', {  props: ['name'],  template: '<p>Hi {{ name }}</p>'})
    new Vue({  el: '#app'})

    See on JSFiddle

    在JSFiddle上查看

    What are we doing? We are initializing a Vue root component on #app, and inside that, we use the Vue component user-name, which abstracts our greeting to the user.

    我们在做什么? 我们正在#app上初始化Vue根组件,在其中,我们使用Vue组件user-name ,它抽象了向用户的问候。

    The component accepts a prop, which is an attribute we use to pass data down to child components.

    组件接受道具,这是我们用来将数据向下传递给子组件的属性。

    In the Vue.component() call we passed user-name as the first parameter. This gives the component a name. You can write the name in 2 ways here. The first is the one we used, called kebab-case. The second is called PascalCase, which is like camelCase, but with the first letter capitalized:

    Vue.component()调用中,我们传递了user-name作为第一个参数。 这为组件命名。 您可以在此处以两种方式输入名称。 第一个是我们使用的那个,叫做kebab-case。 第二个称为PascalCase,类似于camelCase,但是第一个字母大写:

    Vue.component('UserName', {  /* ... */})

    Vue automatically creates an alias internally from user-name to UserName, and vice versa, so you can use whatever you like. It's generally best to use UserName in the JavaScript, and user-name in the template.

    Vue会在内部从user-nameUserName自动创建别名,反之亦然,因此您可以随意使用。 通常最好在JavaScript中使用UserName ,在模板中使用user-name

    本地组件 (Local components)

    Any component created using Vue.component() is globally registered. You don't need to assign it to a variable or pass it around to reuse it in your templates.

    使用Vue.component()创建的任何组件都是全局注册的。 您无需将其分配给变量或将其传递以在模板中重复使用。

    You can encapsulate components locally by assigning an object that defines the component object to a variable:

    您可以通过将定义组件对象的对象分配给变量来在本地封装组件:

    const Sidebar = {  template: '<aside>Sidebar</aside>'}

    and then make it available inside another component by using the components property:

    然后使用components属性使其在另一个组件内部可用:

    new Vue({  el: '#app',  components: {    Sidebar  }})

    You can write the component in the same file, but a great way to do this is to use JavaScript modules:

    您可以在同一文件中编写组件,但是一种很好的方法是使用JavaScript模块:

    import Sidebar from './Sidebar'
    export default {  el: '#app',  components: {    Sidebar  }}

    重用组件 (Reusing a component)

    A child component can be added multiple times. Each separate instance is independent of the others:

    子组件可以添加多次。 每个单独的实例都独立于其他实例:

    <div id="app">  <user-name name="Flavio"></user-name>  <user-name name="Roger"></user-name>  <user-name name="Syd"></user-name></div>
    Vue.component('user-name', {  props: ['name'],  template: '<p>Hi {{ name }}</p>'})
    new Vue({  el: '#app'})

    See on JSFiddle

    在JSFiddle上查看

    组件的组成部分 (The building blocks of a component)

    So far we’ve seen how a component can accept the el, props and template properties.

    到目前为止,我们已经看到了组件如何接受elpropstemplate属性。

    • el is only used in root components initialized using new Vue({}), and identifies the DOM element the component will mount on.

      el仅在使用new Vue({})初始化的根组件中使用,并标识组件将安装在其上的DOM元素。

    • props lists all the properties that we can pass down to a child component

      props列出了我们可以传递给子组件的所有属性

    • template is where we can set up the component template, which will be responsible for defining the output the component generates.

      template是我们可以在其中设置组件模板的地方,它将负责定义组件生成的输出。

    A component accepts other properties:

    组件接受其他属性:

    • data the component local state

      data组件本地状态

    • methods: the component methods

      methods :组件方法

    • computed: the computed properties associated with the component

      computed :与组件关联的计算属性

    • watch: the component watchers

      watch :组件观察者

    单个文件组件 (Single File Components)

    A Vue component can be declared in a JavaScript file (.js) like this:

    可以在JavaScript文件( .js )中声明Vue组件,如下所示:

    Vue.component('component-name', {  /* options */})

    or also:

    或者:

    new Vue({  /* options */})

    or it can be specified in a .vue file.

    或者可以在.vue文件中指定。

    The .vue file is pretty cool because it allows you to define:

    .vue文件非常酷,因为它允许您定义:

    • JavaScript logic

      JavaScript逻辑
    • HTML code template

      HTML代码模板
    • CSS styling

      CSS样式

    all in just a single file. As such it got the name of Single File Component.

    全部都在一个文件中。 因此,它的名称为“单个文件组件”。

    Here’s an example:

    这是一个例子:

    <template>  <p>{{ hello }}</p></template>
    <script>export default {  data() {    return {      hello: 'Hello World!'    }  }}</script>
    <style scoped>  p {    color: blue;  }</style>

    All of this is possible thanks to the use of Webpack. The Vue CLI makes this very easy and supported out of the box. .vuefiles cannot be used without a Webpack setup, and as such, they are not very suited to apps that just use Vue on a page without being a full-blown single-page app (SPA).

    由于使用了Webpack,所有这些都是可能的。 Vue CLI使得此操作非常容易,并且开箱即用。 .vue文件必须在没有Webpack设置的情况下才能使用,因此,它们非常不适合仅在页面上使用Vue而又不是完整的单页应用程序(SPA)的应用程序。

    Since Single File Components rely on Webpack, we get for free the ability to use modern Web features.

    由于单个文件组件依赖Webpack,因此我们免费获得了使用现代Web功能的功能。

    Your CSS can be defined using SCSS or Stylus, the template can be built using Pug, and all you need to do to make this happen is to declare to Vue which language preprocessor you are going to use.

    可以使用SCSS或Stylus定义CSS,可以使用Pug构建模板,而要做的就是向Vue声明要使用哪种语言预处理器。

    The list of supported preprocessors include

    支持的预处理器列表包括

    • TypeScript

      打字稿
    • SCSS

      SCSS
    • Sass

      萨斯
    • Less

    • PostCSS

      PostCSS
    • Pug

      哈巴狗

    We can use modern JavaScript (ES6–7–8) regardless of the target browser using the Babel integration, and ES Modules too, so we can use import/export statements.

    We can use modern JavaScript (ES6–7–8) regardless of the target browser using the Babel integration, and ES Modules too, so we can use import/export statements.

    We can use CSS Modules to scope our CSS.

    We can use CSS Modules to scope our CSS.

    Speaking of scoping CSS, Single File Components make it absolutely easy to write CSS that won’t leak to other components, by using <style scoped> tags.

    Speaking of scoping CSS, Single File Components make it absolutely easy to write CSS that won't leak to other components, by using <style scop ed> tags.

    If you omit scoped, the CSS you define will be global. But adding the scoped tag, Vue automatically adds a specific class to the component, unique to your app, so the CSS is guaranteed to not leak out to other components.

    If you omit scoped , the CSS you define will be global. But adding the scoped tag, Vue automatically adds a specific class to the component, unique to your app, so the CSS is guaranteed to not leak out to other components.

    Maybe your JavaScript is huge because of some logic you need to take care of. What if you want to use a separate file for your JavaScript?

    Maybe your JavaScript is huge because of some logic you need to take care of. What if you want to use a separate file for your JavaScript?

    You can use the src attribute to externalize it:

    You can use the src attribute to externalize it:

    <template>  <p>{{ hello }}</p></template><script src="./hello.js"></script>

    This also works for your CSS:

    This also works for your CSS:

    <template>  <p>{{ hello }}</p></template><script src="./hello.js"></script><style src="./hello.css"></style>

    Notice how I used

    Notice how I used

    export default {  data() {    return {      hello: 'Hello World!'    }  }}

    in the component’s JavaScript to set up the data.

    in the component's JavaScript to set up the data.

    Other common ways you will see are:

    Other common ways you will see are:

    export default {  data: function() {    return {      name: 'Flavio'    }  }}

    The above is equivalent to what we did before.

    The above is equivalent to what we did before.

    Or:

    要么:

    export default {  data: () => {    return {      name: 'Flavio'    }  }}

    This is different, because it uses an arrow function. Arrow functions are fine until we need to access a component method. This is an issue if we need to make use of this, and such property is not bound to the component using arrow functions. So it's mandatory to use regular functions rather than arrow functions.

    This is different, because it uses an arrow function. Arrow functions are fine until we need to access a component method. This is an issue if we need to make use of this , and such property is not bound to the component using arrow functions. So it's mandatory to use regular functions rather than arrow functions.

    You might also see:

    You might also see:

    module.exports = {  data: () => {    return {      name: 'Flavio'    }  }}

    This is using the CommonJS syntax and it works as well. But I recommend using the ES Modules syntax, as that is a JavaScript standard.

    This is using the CommonJS syntax and it works as well. But I recommend using the ES Modules syntax, as that is a JavaScript standard.

    Vue Templates (Vue Templates)

    Vue.js uses a templating language that’s a superset of HTML.

    Vue.js uses a templating language that's a superset of HTML.

    Any HTML is a valid Vue.js template. In addition to that, Vue.js provides two powerful things: interpolation and directives.

    Any HTML is a valid Vue.js template. In addition to that, Vue.js provides two powerful things: interpolation and directives.

    This is a valid Vue.js template:

    This is a valid Vue.js template:

    <span>Hello!</span>

    This template can be put inside a Vue component declared explicitly:

    This template can be put inside a Vue component declared explicitly:

    new Vue({  template: '<span>Hello!</span>'})

    or it can be put into a Single File Component:

    or it can be put into a Single File Component:

    <template>  <span>Hello!</span></template>

    This first example is very basic. The next step is making it output a piece of the component state, for example, a name.

    This first example is very basic. The next step is making it output a piece of the component state, for example, a name.

    This can be done using interpolation. First, we add some data to our component:

    This can be done using interpolation. First, we add some data to our component:

    new Vue({  
      data: {    
        name: 'Flavio'  
      },  
      template: '<span>Hello!</span>'
    })

    and then we can add it to our template using the double brackets syntax:

    and then we can add it to our template using the double brackets syntax:

    new Vue({  data: {    name: 'Flavio'  },  template: '<span>Hello {{name}}!</span>'})

    One interesting thing here. See how we just used name instead of this.data.name?

    One interesting thing here. See how we just used name instead of this.data.name ?

    This is because Vue.js does some internal binding and lets the template use the property as if it was local. Pretty handy.

    This is because Vue.js does some internal binding and lets the template use the property as if it was local. 很方便。

    In a single file component, that would be:

    In a single file component, that would be:

    <template>  <span>Hello {{name}}!</span></template>
    <script>export default {  data() {    return {      name: 'Flavio'    }  }}</script>

    I used a regular function in my export. Why not an arrow function?

    I used a regular function in my export. Why not an arrow function?

    This is because in data we might need to access a method in our component instance, and we can't do that if this is not bound to the component, so we can’t use an arrow function.

    This is because in data we might need to access a method in our component instance, and we can't do that if this is not bound to the component, so we can't use an arrow function.

    Do note that we could use an arrow function, but then I would need to remember to switch to a regular function in case I use this. Better play it safe, I think.

    Do note that we could use an arrow function, but then I would need to remember to switch to a regular function in case I use this . Better play it safe, I think.

    Now, back to the interpolation.

    Now, back to the interpolation.

    {{ name }} should remind you of Mustache / Handlebars template interpolation, but it's just a visual reminder.

    {{ name }} should remind you of Mustache / Handlebars template interpolation, but it's just a visual reminder.

    While in those templating engines they are “dumb”, in Vue, you can do much more, and it’s more flexible.

    While in those templating engines they are “dumb”, in Vue, you can do much more, and it's more flexible.

    You can use any JavaScript expression inside your interpolations, but you’re limited to just one expression:

    You can use any JavaScript expression inside your interpolations, but you're limited to just one expression:

    {{ name.reverse() }}
    {{ name === 'Flavio' ? 'Flavio' : 'stranger' }}

    Vue provides access to some global objects inside templates, including Math and Date, so you can use them:

    Vue provides access to some global objects inside templates, including Math and Date, so you can use them:

    {{ Math.sqrt(16) * Math.random() }}

    It’s best to avoid adding complex logic to templates, but the fact that Vue allows it gives us more flexibility, especially when trying things out.

    It's best to avoid adding complex logic to templates, but the fact that Vue allows it gives us more flexibility, especially when trying things out.

    We can first try to put an expression in the template, and then move it to a computed property or method later on.

    We can first try to put an expression in the template, and then move it to a computed property or method later on.

    The value included in any interpolation will be updated upon a change of any of the data properties it relies on.

    The value included in any interpolation will be updated upon a change of any of the data properties it relies on.

    You can avoid this reactivity by using the v-once directive.

    You can avoid this reactivity by using the v-once directive.

    The result is always escaped, so you can’t have HTML in the output.

    The result is always escaped, so you can't have HTML in the output.

    If you need to have an HTML snippet, you need to use the v-html directive instead.

    If you need to have an HTML snippet, you need to use the v-html directive instead.

    Styling components using CSS (Styling components using CSS)

    The simplest option to add CSS to a Vue.js component is to use the style tag, just like in HTML:

    The simplest option to add CSS to a Vue.js component is to use the style tag, just like in HTML:

    <template>  <p style="text-decoration: underline">Hi!</p></template>
    <script>export default {  data() {    return {      decoration: 'underline'    }  }}</script>

    This is as static as you can get. What if you want underline to be defined in the component data? Here's how you can do it:

    This is as static as you can get. What if you want underline to be defined in the component data? 方法如下:

    <template>  <p :style="{'text-decoration': decoration}">Hi!</p></template>
    <script>export default {  data() {    return {      decoration: 'underline'    }  }}</script>

    :style is a shorthand for v-bind:style. I'll use this shorthand throughout this tutorial.

    :style is a shorthand for v-bind:style . I'll use this shorthand throughout this tutorial.

    Notice how we had to wrap text-decoration in quotes. This is because of the dash, which is not part of a valid JavaScript identifier.

    Notice how we had to wrap text-decoration in quotes. This is because of the dash, which is not part of a valid JavaScript identifier.

    You can avoid the quotes by using a special camelCase syntax that Vue.js enables, and rewriting it to textDecoration:

    You can avoid the quotes by using a special camelCase syntax that Vue.js enables, and rewriting it to textDecoration :

    <template>  <p :style="{textDecoration: decoration}">Hi!</p></template>

    Instead of binding an object to style, you can reference a computed property:

    Instead of binding an object to style , you can reference a computed property:

    <template>  <p :style="styling">Hi!</p></template>
    <script>export default {  data() {    return {      textDecoration: 'underline',      textWeight: 'bold'    }  },  computed: {    styling: function() {      return {        textDecoration: this.textDecoration,        textWeight: this.textWeight      }    }  }}</script>

    Vue components generate plain HTML, so you can choose to add a class to each element, and add a corresponding CSS selector with properties that style it:

    Vue components generate plain HTML, so you can choose to add a class to each element, and add a corresponding CSS selector with properties that style it:

    <template>  <p class="underline">Hi!</p></template>
    <style>.underline { text-decoration: underline; }</style>

    You can use SCSS like this:

    You can use SCSS like this:

    <template>  <p class="underline">Hi!</p></template>
    <style lang="scss">body {  .underline { text-decoration: underline; }}</style>

    You can hard code the class like in the above example. Or you can bind the class to a component property, to make it dynamic, and only apply to that class if the data property is true:

    You can hard code the class like in the above example. Or you can bind the class to a component property, to make it dynamic, and only apply to that class if the data property is true:

    <template>  <p :class="{underline: isUnderlined}">Hi!</p></template>
    <script>export default {  data() {    return {      isUnderlined: true    }  }}</script>
    <style>.underline { text-decoration: underline; }</style>

    Instead of binding an object to class, like we did with <p :class="{text: isText}">Hi!</p>, you can directly bind a string, and that will reference a data property:

    Instead of binding an object to class, like we did with <p :class="{text: isText}">H i!</p>, you can directly bind a string, and that will reference a data property:

    <template>  <p :class="paragraphClass">Hi!</p></template>
    <script>export default {  data() {    return {      paragraphClass: 'underline'    }  }}</script>
    <style>.underline { text-decoration: underline; }</style>

    You can assign multiple classes, either by adding two classes to paragraphClass in this case or by using an array:

    You can assign multiple classes, either by adding two classes to paragraphClass in this case or by using an array:

    <template>  <p :class="[decoration, weight]">Hi!</p></template>
    <script>export default {  data() {    return {      decoration: 'underline',      weight: 'weight',    }  }}</script>
    <style>.underline { text-decoration: underline; }.weight { font-weight: bold; }</style>

    The same can be done using an object inlined in the class binding:

    The same can be done using an object inlined in the class binding:

    <template>  <p :class="{underline: isUnderlined, weight: isBold}">Hi!</p></template>
    <script>export default {  data() {    return {      isUnderlined: true,      isBold: true    }  }}</script>
    <style>.underline { text-decoration: underline; }.weight { font-weight: bold; }</style>

    And you can combine the two statements:

    And you can combine the two statements:

    <template>  <p :class="[decoration, {weight: isBold}]">Hi!</p></template>
    <script>export default {  data() {    return {      decoration: 'underline',      isBold: true    }  }}</script>
    <style>.underline { text-decoration: underline; }.weight { font-weight: bold; }</style>

    You can also use a computed property that returns an object, which works best when you have many CSS classes to add to the same element:

    You can also use a computed property that returns an object, which works best when you have many CSS classes to add to the same element:

    <template>  <p :class="paragraphClasses">Hi!</p></template>
    <script>export default {  data() {    return {      isUnderlined: true,      isBold: true    }  },  computed: {    paragraphClasses: function() {      return {        underlined: this.isUnderlined,        bold: this.isBold      }    }  }}</script>
    <style>.underlined { text-decoration: underline; }.bold { font-weight: bold; }</style>

    Notice that in the computed property you need to reference the component data using this.[propertyName], while in the template data, properties are conveniently put as first-level properties.

    Notice that in the computed property you need to reference the component data using this.[propertyName] , while in the template data, properties are conveniently put as first-level properties.

    Any CSS that’s not hard coded like in the first example is going to be processed by Vue, and Vue does the nice job of automatically prefixing the CSS for us. This allows us to write clean CSS while still targeting older browsers (which still means browsers that Vue supports, so IE9+).

    Any CSS that's not hard coded like in the first example is going to be processed by Vue, and Vue does the nice job of automatically prefixing the CSS for us. This allows us to write clean CSS while still targeting older browsers (which still means browsers that Vue supports, so IE9+).

    指令 (Directives)

    We saw in Vue.js templates and interpolations how you can embed data in Vue templates.

    We saw in Vue.js templates and interpolations how you can embed data in Vue templates.

    This section explains the other technique offered by Vue.js in templates: directives.

    This section explains the other technique offered by Vue.js in templates: directives.

    Directives are basically like HTML attributes which are added inside templates. They all start with v-, to indicate that's a Vue special attribute.

    Directives are basically like HTML attributes which are added inside templates. They all start with v- , to indicate that's a Vue special attribute.

    Let’s see each of the Vue directives in detail.

    Let's see each of the Vue directives in detail.

    v-text (v-text)

    Instead of using interpolation, you can use the v-text directive. It performs the same job:

    Instead of using interpolation, you can use the v-text directive. It performs the same job:

    <span v-text="name"></span>

    v-once (v-once)

    You know how {{ name }} binds to the name property of the component data.

    You know how {{ name }} binds to the name property of the component data.

    Any time name changes in your component data, Vue is going to update the value represented in the browser.

    Any time name changes in your component data, Vue is going to update the value represented in the browser.

    Unless you use the v-once directive, which is basically like an HTML attribute:

    Unless you use the v-once directive, which is basically like an HTML attribute:

    <span v-once>{{ name }}</span>

    v-html (v-html)

    When you use interpolation to print a data property, the HTML is escaped. This is a great way that Vue uses to automatically protect from XSS attacks.

    When you use interpolation to print a data property, the HTML is escaped. This is a great way that Vue uses to automatically protect from XSS attacks.

    There are cases, however, where you want to output HTML and make the browser interpret it. You can use the v-htmldirective:

    There are cases, however, where you want to output HTML and make the browser interpret it. You can use the v-html directive:

    <span v-html="someHtml"></span>

    v-bind (v-bind)

    Interpolation only works in the tag content. You can’t use it on attributes.

    Interpolation only works in the tag content. You can't use it on attributes.

    Attributes must use v-bind:

    Attributes must use v-bind :

    <a v-bind:href="url">{{ linkText }}</a>

    v-bind is so common that there is a shorthand syntax for it:

    v-bind is so common that there is a shorthand syntax for it:

    <a v-bind:href="url">{{ linkText }}</a><a :href="url">{{ linkText }}</a>

    Two-way binding using v-model (Two-way binding using v-model)

    v-model lets us bind a form input element for example, and makes it change the Vue data property when the user changes the content of the field:

    v-model lets us bind a form input element for example, and makes it change the Vue data property when the user changes the content of the field:

    <input v-model="message" placeholder="Enter a message"><p>Message is: {{ message }}</p>
    <select v-model="selected">  <option disabled value="">Choose a fruit</option>  <option>Apple</option>  <option>Banana</option>  <option>Strawberry</option></select><span>Fruit chosen: {{ selected }}</span>

    Using expressions (Using expressions)

    You can use any JavaScript expression inside a directive:

    You can use any JavaScript expression inside a directive:

    <span v-text="'Hi, ' + name + '!'"></span>
    <a v-bind:href="'https://' + domain + path">{{ linkText }}</a>

    Any variable used in a directive references the corresponding data property.

    Any variable used in a directive references the corresponding data property.

    有条件的 (Conditionals)

    Inside a directive you can use the ternary operator to perform a conditional check, since that’s an expression:

    Inside a directive you can use the ternary operator to perform a conditional check, since that's an expression:

    <span v-text="name == Flavio ? 'Hi Flavio!' : 'Hi' + name + '!'"></span>

    There are dedicated directives that allow you to perform more organized conditionals: v-if, v-else and v-else-if.

    There are dedicated directives that allow you to perform more organized conditionals: v-if , v-else and v-else-if .

    <p v-if="shouldShowThis">Hey!</p>

    shouldShowThis is a boolean value contained in the component's data.

    shouldShowThis is a boolean value contained in the component's data.

    循环 (Loops)

    v-for allows you to render a list of items. Use it in combination with v-bind to set the properties of each item in the list.

    v-for allows you to render a list of items. Use it in combination with v-bind to set the properties of each item in the list.

    You can iterate on a simple array of values:

    You can iterate on a simple array of values:

    <template>  <ul>    <li v-for="item in items">{{ item }}</li>  </ul></template>
    <script>export default {  data() {    return {      items: ['car', 'bike', 'dog']    }  }}</script>

    Or on an array of objects:

    Or on an array of objects:

    <template>  <div>    <!-- using interpolation -->    <ul>      <li v-for="todo in todos">{{ todo.title }}</li>    </ul>    <!-- using v-text -->    <ul>      <li v-for="todo in todos" v-text="todo.title"></li>    </ul>  </div></template>
    <script>export default {  data() {    return {      todos: [        { id: 1, title: 'Do something' },        { id: 2, title: 'Do something else' }      ]    }  }}</script>

    v-for can give you the index using:

    v-for can give you the index using:

    <li v-for="(todo, index) in todos"></li>

    大事记 (Events)

    v-on allows you to listen to DOM events, and trigger a method when the event happens. Here we listen for a click event:

    v-on allows you to listen to DOM events, and trigger a method when the event happens. Here we listen for a click event:

    <template>  <a v-on:click="handleClick">Click me!</a></template>
    <script>export default {  methods: {    handleClick: function() {      alert('test')    }  }}</script>

    You can pass parameters to any event:

    You can pass parameters to any event:

    <template>  <a v-on:click="handleClick('test')">Click me!</a></template>
    <script>export default {  methods: {    handleClick: function(value) {      alert(value)    }  }}</script>

    Small bits of JavaScript (a single expression) can be put directly into the template:

    Small bits of JavaScript (a single expression) can be put directly into the template:

    <template>  <a v-on:click="counter = counter + 1">{{counter}}</a></template>
    <script>export default {  data: function() {    return {      counter: 0    }  }}</script>

    click is just one kind of event. A common event is submit, which you can bind using v-on:submit.

    click is just one kind of event. A common event is submit , which you can bind using v-on:submit .

    v-on is so common that there is a shorthand syntax for it, @:

    v-on is so common that there is a shorthand syntax for it, @ :

    <a v-on:click="handleClick">Click me!</a><a @click="handleClick">Click me!</a>

    Show or hide (Show or hide)

    You can choose to only show an element in the DOM if a particular property of the Vue instance evaluates to true, using v-show:

    You can choose to only show an element in the DOM if a particular property of the Vue instance evaluates to true, using v-show :

    <p v-show="isTrue">Something</p>

    The element is still inserted in the DOM, but set to display: none if the condition is not satisfied.

    The element is still inserted in the DOM, but set to display: none if the condition is not satisfied.

    Event directive modifiers (Event directive modifiers)

    Vue offers some optional event modifiers you can use in association with v-on, which automatically make the event do something without you explicitly coding it in your event handler.

    Vue offers some optional event modifiers you can use in association with v-on , which automatically make the event do something without you explicitly coding it in your event handler.

    One good example is .prevent, which automatically calls preventDefault() on the event.

    One good example is .prevent , which automatically calls preventDefault() on the event.

    In this case, the form does not cause the page to be reloaded, which is the default behavior:

    In this case, the form does not cause the page to be reloaded, which is the default behavior:

    <form v-on:submit.prevent="formSubmitted"></form>

    Other modifiers include .stop, .capture, .self, .once, .passive and they are described in detail in the official docs.

    Other modifiers include .stop , .capture , .self , .once , .passive and they are described in detail in the official docs .

    Custom directives (Custom directives)

    The Vue default directives already let you do a lot of work, but you can always add new, custom directives if you want.

    The Vue default directives already let you do a lot of work, but you can always add new, custom directives if you want.

    Read here if you’re interested in learning more.

    Read here if you're interested in learning more.

    方法 (Methods)

    What are Vue.js methods? (What are Vue.js methods?)

    A Vue method is a function associated with the Vue instance.

    A Vue method is a function associated with the Vue instance.

    Methods are defined inside the methods property:

    Methods are defined inside the methods property:

    new Vue({  methods: {    handleClick: function() {      alert('test')    }  }})

    or in the case of Single File Components:

    or in the case of Single File Components:

    <script>export default {  methods: {    handleClick: function() {      alert('test')    }  }}</script>

    Methods are especially useful when you need to perform an action and you attach a v-on directive on an element to handle events. Like this one, which calls handleClick when the element is clicked:

    Methods are especially useful when you need to perform an action and you attach a v-on directive on an element to handle events. Like this one, which calls handleClick when the element is clicked:

    <template>  <a @click="handleClick">Click me!</a></template>

    Pass parameters to Vue.js methods (Pass parameters to Vue.js methods)

    Methods can accept parameters.

    Methods can accept parameters.

    In this case, you just pass the parameter in the template:

    In this case, you just pass the parameter in the template:

    <template>  <a @click="handleClick('something')">Click me!</a></template>
    new Vue({  methods: {    handleClick: function(text) {      alert(text)    }  }})

    or in the case of Single File Components:

    or in the case of Single File Components:

    <script>export default {  methods: {    handleClick: function(text) {      alert(text)    }  }}</script>

    How to access data from a method (How to access data from a method)

    You can access any of the data properties of the Vue component by using this.propertyName:

    You can access any of the data properties of the Vue component by using this.propertyName :

    <template>  <a @click="handleClick()">Click me!</a></template>
    <script>export default {  data() {    return {      name: 'Flavio'    }  },  methods: {    handleClick: function() {      console.log(this.name)    }  }}</script>

    We don’t have to use this.data.name, just this.name. Vue does provide a transparent binding for us. Using this.data.name will raise an error.

    We don't have to use this.data.name , just this.name . Vue does provide a transparent binding for us. Using this.data.name will raise an error.

    As you saw before in the events description, methods are closely interlinked to events, because they are used as event handlers. Every time an event occurs, that method is called.

    As you saw before in the events description, methods are closely interlinked to events, because they are used as event handlers. Every time an event occurs, that method is called.

    Watchers (Watchers)

    A watcher is a special Vue.js feature that allows you to spy on one property of the component state, and run a function when that property value changes.

    A watcher is a special Vue.js feature that allows you to spy on one property of the component state, and run a function when that property value changes.

    Here’s an example. We have a component that shows a name, and allows you to change it by clicking a button:

    这是一个例子。 We have a component that shows a name, and allows you to change it by clicking a button:

    <template>  <p>My name is {{name}}</p>  <button @click="changeName()">Change my name!</button></template>
    <script>export default {  data() {    return {      name: 'Flavio'    }  },  methods: {    changeName: function() {      this.name = 'Flavius'    }  }}</script>

    When the name changes we want to do something, like print a console log.

    When the name changes we want to do something, like print a console log.

    We can do so by adding to the watch object a property named as the data property we want to watch over:

    We can do so by adding to the watch object a property named as the data property we want to watch over:

    <script>export default {  data() {    return {      name: 'Flavio'    }  },  methods: {    changeName: function() {      this.name = 'Flavius'    }  },  watch: {    name: function() {      console.log(this.name)    }  }}</script>

    The function assigned to watch.name can optionally accept 2 parameters. The first is the new property value. The second is the old property value:

    The function assigned to watch.name can optionally accept 2 parameters. The first is the new property value. The second is the old property value:

    <script>export default {  /* ... */  watch: {    name: function(newValue, oldValue) {      console.log(newValue, oldValue)    }  }}</script>

    Watchers cannot be looked up from a template as you can with computed properties.

    Watchers cannot be looked up from a template as you can with computed properties.

    Computed Properties (Computed Properties)

    What is a Computed Property (What is a Computed Property)

    In Vue.js you can output any data value using parentheses:

    In Vue.js you can output any data value using parentheses:

    <template>  <p>{{ count }}</p></template>
    <script>export default {  data() {    return {      count: 1    }  }}</script>

    This property can host some small computations. For example:

    This property can host some small computations. 例如:

    <template>  {{ count * 10 }}</template>

    But you’re limited to a single JavaScript expression.

    But you're limited to a single JavaScript expression .

    In addition to this technical limitation, you also need to consider that templates should only be concerned with displaying data to the user, not perform logic computations.

    In addition to this technical limitation, you also need to consider that templates should only be concerned with displaying data to the user, not perform logic computations.

    To do something more than a single expression, and to have more declarative templates, you use a computed property.

    To do something more than a single expression, and to have more declarative templates, you use a computed property.

    Computed properties are defined in the computed property of the Vue component:

    Computed properties are defined in the computed property of the Vue component:

    <script>export default {  computed: {
    }}</script>

    An example of a computed property (An example of a computed property)

    Here’s an example that uses a computed property count to calculate the output.

    Here's an example that uses a computed property count to calculate the output.

    Notice:

    注意:

    1. I didn’t have to call {{ count() }}. Vue.js automatically invokes the function

      I didn't have to call {{ count() }} . Vue.js automatically invokes the function

    2. I used a regular function (not an arrow function) to define the count computed property, because I need to be able to access the component instance through this.

      I used a regular function (not an arrow function) to define the count computed property, because I need to be able to access the component instance through this .

    <template>  <p>{{ count }}</p></template>
    <script>export default {  data() {    return {      items: [1, 2, 3]    }  },  computed: {    count: function() {      return 'The count is ' + this.items.length * 10    }  }}</script>

    Computed properties vs. methods (Computed properties vs. methods)

    If you already know about Vue methods, you may wonder what’s the difference.

    If you already know about Vue methods, you may wonder what's the difference.

    First, methods must be called, not just referenced, so you’d need to do:

    First, methods must be called, not just referenced, so you'd need to do:

    <template>  <p>{{ count() }}</p></template>
    <script>export default {  data() {    return {      items: [1, 2, 3]    }  },  methods: {    count: function() {      return 'The count is ' + this.items.length * 10    }  }}</script>

    But the main difference is that computed properties are cached.

    But the main difference is that computed properties are cached.

    The result of the count computed property is internally cached until the items data property changes.

    The result of the count computed property is internally cached until the items data property changes.

    Important: Computed properties are only updated when a reactive source updates. Regular JavaScript methods are not reactive, so a common example is to use Date.now():

    Important: Computed properties are only updated when a reactive source updates. Regular JavaScript methods are not reactive, so a common example is to use Date.now() :

    <template>  <p>{{ now }}</p></template>
    <script>export default {  computed: {    now: function () {      return Date.now()    }  }}</script>

    It will render once, and then it will not be updated even when the component re-renders. It’s just updated on a page refresh, when the Vue component is quit and reinitialized.

    It will render once, and then it will not be updated even when the component re-renders. It's just updated on a page refresh, when the Vue component is quit and reinitialized.

    In this case, a method is better suited for your needs.

    In this case, a method is better suited for your needs.

    Methods vs. Watchers vs. Computed Properties (Methods vs. Watchers vs. Computed Properties)

    Now that you know about methods, watchers and computed properties, you might be wondering when should you use one vs the others.

    Now that you know about methods, watchers and computed properties, you might be wondering when should you use one vs the others.

    Here’s a breakdown of this question.

    Here's a breakdown of this question.

    When to use methods (When to use methods)

    • To react to some event happening in the DOM

      To react to some event happening in the DOM
    • To call a function when something happens in your component.

      To call a function when something happens in your component.

      You can call a method from computed properties or watchers.

      You can call a method from computed properties or watchers.

    When to use computed properties (When to use computed properties)

    • You need to compose new data from existing data sources

      You need to compose new data from existing data sources
    • You have a variable you use in your template that’s built from one or more data properties

      You have a variable you use in your template that's built from one or more data properties
    • You want to reduce a complicated, nested property name to a more readable and easy to use one (but update it when the original property changes)

      You want to reduce a complicated, nested property name to a more readable and easy to use one (but update it when the original property changes)
    • You need to reference a value from the template. In this case, creating a computed property is the best thing, because it’s cached.

      You need to reference a value from the template. In this case, creating a computed property is the best thing, because it's cached.
    • You need to listen to changes of more than one data property

      You need to listen to changes of more than one data property

    When to use watchers (When to use watchers)

    • You want to listen when a data property changes, and perform some action

      You want to listen when a data property changes, and perform some action
    • You want to listen to a prop value change

      You want to listen to a prop value change
    • You only need to listen to one specific property (you can’t watch multiple properties at the same time)

      You only need to listen to one specific property (you can't watch multiple properties at the same time)
    • You want to watch a data property until it reaches some specific value and then do something

      You want to watch a data property until it reaches some specific value and then do something

    Props: pass data to child components (Props: pass data to child components)

    Props are the way components can accept data from components that include them (parent components).

    Props are the way components can accept data from components that include them (parent components).

    When a component expects one or more prop, it must define them in its props property:

    When a component expects one or more prop, it must define them in its props property:

    Vue.component('user-name', {  props: ['name'],  template: '<p>Hi {{ name }}</p>'})

    or, in a Vue Single File Component:

    or, in a Vue Single File Component:

    <template>  <p>{{ name }}</p></template>
    <script>export default {  props: ['name']}</script>

    Accept multiple props (Accept multiple props)

    You can have multiple props by simply appending them to the array:

    You can have multiple props by simply appending them to the array:

    Vue.component('user-name', {  props: ['firstName', 'lastName'],  template: '<p>Hi {{ firstName }} {{ lastName }}</p>'})

    Set the prop type (Set the prop type)

    You can specify the type of a prop very simply by using an object instead of an array, using the name of the property as the key of each property, and the type as the value:

    You can specify the type of a prop very simply by using an object instead of an array, using the name of the property as the key of each property, and the type as the value:

    Vue.component('user-name', {  props: {    firstName: String,    lastName: String  },  template: '<p>Hi {{ firstName }} {{ lastName }}</p>'})

    The valid types you can use are:

    The valid types you can use are:

    • String

    • Number

    • Boolean

      布尔型
    • Array

      数组
    • Object

      目的
    • Date

      日期
    • Function

      Function
    • Symbol

      Symbol

    When a type mismatches, Vue alerts you (in development mode) in the console with a warning.

    When a type mismatches, Vue alerts you (in development mode) in the console with a warning.

    Prop types can be more articulated.

    Prop types can be more articulated.

    You can allow multiple different value types:

    You can allow multiple different value types:

    props: {  firstName: [String, Number]}

    Set a prop to be mandatory (Set a prop to be mandatory)

    You can require a prop to be mandatory:

    You can require a prop to be mandatory:

    props: {  firstName: {    type: String,    required: true  }}

    Set the default value of a prop (Set the default value of a prop)

    You can specify a default value:

    You can specify a default value:

    props: {  firstName: {    type: String,    default: 'Unknown person'  }}

    For objects:

    For objects:

    props: {  name: {    type: Object,    default: {      firstName: 'Unknown',      lastName: ''    }  }}

    default can also be a function that returns an appropriate value, rather than being the actual value.

    default can also be a function that returns an appropriate value, rather than being the actual value.

    You can even build a custom validator, which is cool for complex data:

    You can even build a custom validator, which is cool for complex data:

    props: {  name: {    validator: name => {      return name === 'Flavio' //only allow "Flavios"    }  }}

    Passing props to the component (Passing props to the component)

    You pass a prop to a component using the syntax

    You pass a prop to a component using the syntax

    <ComponentName color="white" />

    if what you pass is a static value.

    if what you pass is a static value.

    If it’s a data property, you use

    If it's a data property, you use

    <template>  <ComponentName :color=color /></template>
    <script>...export default {  //...  data: function() {    return {      color: 'white'    }  },  //...}</script>

    You can use a ternary operator inside the prop value to check a truthy condition and pass a value that depends on it:

    You can use a ternary operator inside the prop value to check a truthy condition and pass a value that depends on it:

    <template>  <ComponentName :colored="color == 'white' ? true : false" /></template>
    <script>...export default {  //...  data: function() {    return {      color: 'white'    }  },  //...}</script>

    Handling Events in Vue (Handling Events in Vue)

    What are Vue.js events? (What are Vue.js events?)

    Vue.js allows us to intercept any DOM event by using the v-on directive on an element.

    Vue.js allows us to intercept any DOM event by using the v-on directive on an element.

    If we want to do something when a click event happens in this element:

    If we want to do something when a click event happens in this element:

    <template>  <a>Click me!</a></template>

    we add a v-on directive:

    we add a v-on directive:

    <template>  <a v-on:click="handleClick">Click me!</a></template>

    Vue also offers a very convenient alternative syntax for this:

    Vue also offers a very convenient alternative syntax for this:

    <template>  <a @click="handleClick">Click me!</a></template>

    You can choose to use the parentheses or not. @click="handleClick" is equivalent to @click="handleClick()".

    You can choose to use the parentheses or not. @click="handleClick" is equivalent to @click="handleClick()" .

    handleClick is a method attached to the component:

    handleClick is a method attached to the component:

    <script>export default {  methods: {    handleClick: function(event) {      console.log(event)    }  }}</script>

    What you need to know here is that you can pass parameters from events: @click="handleClick(param)" and they will be received inside the method.

    What you need to know here is that you can pass parameters from events: @click="handleClick(param)" and they will be received inside the method.

    Access the original event object (Access the original event object)

    In many cases, you will want to perform an action on the event object or look up some property in it. How can you access it?

    In many cases, you will want to perform an action on the event object or look up some property in it. How can you access it?

    Use the special $event directive:

    Use the special $event directive:

    <template>  <a @click="handleClick($event)">Click me!</a></template>
    <script>export default {  methods: {    handleClick: function(event) {      console.log(event)    }  }}</script>

    and if you already pass a variable:

    and if you already pass a variable:

    <template>  <a @click="handleClick('something', $event)">Click me!</a></template>
    <script>export default {  methods: {    handleClick: function(text, event) {      console.log(text)      console.log(event)    }  }}</script>

    From there you could call event.preventDefault(), but there's a better way: event modifiers.

    From there you could call event.preventDefault() , but there's a better way: event modifiers.

    Event modifiers (Event modifiers)

    Instead of messing with DOM “things” in your methods, tell Vue to handle things for you:

    Instead of messing with DOM “things” in your methods, tell Vue to handle things for you:

    • @click.prevent call event.preventDefault()

      @click.prevent call event.preventDefault()

    • @click.stop call event.stopPropagation()

      @click.stop call event.stopPropagation()

    • @click.passive makes use of the passive option of addEventListener

      @click.passive makes use of the passive option of addEventListener

    • @click.capture uses event capturing instead of event bubbling

      @click.capture uses event capturing instead of event bubbling

    • @click.self make sure the click event was not bubbled from a child event, but directly happened on that element

      @click.self make sure the click event was not bubbled from a child event, but directly happened on that element

    • @click.once the event will only be triggered exactly once

      @click.once the event will only be triggered exactly once

    All those options can be combined by appending one modifier after the other.

    All those options can be combined by appending one modifier after the other.

    For more on propagation, bubbling and capturing, see my JavaScript events guide.

    For more on propagation, bubbling and capturing, see my JavaScript events guide .

    Inject content using slots (Inject content using slots)

    A component can choose to define its content entirely, like in this case:

    A component can choose to define its content entirely, like in this case:

    Vue.component('user-name', {  props: ['name'],  template: '<p>Hi {{ name }}</p>'})

    Or it can also let the parent component inject any kind of content into it, by using slots.

    Or it can also let the parent component inject any kind of content into it, by using slots.

    What’s a slot?

    What's a slot?

    You define it by putting <slot>&lt;/slot> in a component template:

    You define it by putting <slot>& lt;/slot> in a component template:

    Vue.component('user-information', {  template: '<div class="user-information"><slot></slot></div>'})

    When using this component, any content added between the opening and closing tag will be added inside the slot placeholder:

    When using this component, any content added between the opening and closing tag will be added inside the slot placeholder:

    <user-information>  <h2>Hi!</h2>  <user-name name="Flavio"></user-information>

    If you put any content side the <slot>&lt;/slot> tags, that serves as the default content in case nothing is passed in.

    If you put any content side the <slot>& lt;/slot> tags, that serves as the default content in case nothing is passed in.

    A complicated component layout might require a better way to organize content.

    A complicated component layout might require a better way to organize content.

    Enter named slots.

    Enter named slots .

    With a named slot, you can assign parts of a slot to a specific position in your component template layout, and you use a slot attribute to any tag, to assign content to that slot.

    With a named slot, you can assign parts of a slot to a specific position in your component template layout, and you use a slot attribute to any tag, to assign content to that slot.

    Anything outside any template tag is added to the main slot.

    Anything outside any template tag is added to the main slot .

    For convenience, I use a page single file component in this example:

    For convenience, I use a page single file component in this example:

    <template>  <div>    <main>      <slot></slot>    </main>    <sidebar>      <slot name="sidebar"></slot>    </sidebar>  </div></template>
    <page>  <ul slot="sidebar">    <li>Home</li>    <li>Contact</li>  </ul>
    <h2>Page title</h2>  <p>Page content</p></page>

    Filters, helpers for templates (Filters, helpers for templates)

    Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data.

    Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data.

    They don’t change a component’s data or anything, but they only affect the output.

    They don't change a component's data or anything, but they only affect the output.

    Say you are printing a name:

    Say you are printing a name:

    <template>  <p>Hi {{ name }}!</p></template>
    <script>export default {  data() {    return {      name: 'Flavio'    }  }}</script>

    What if you want to check that name is actually containing a value, and if not print 'there', so that our template will print "Hi there!"?

    What if you want to check that name is actually containing a value, and if not print 'there', so that our template will print "Hi there!"?

    Enter filters:

    Enter filters:

    <template>  <p>Hi {{ name | fallback }}!</p></template>
    <script>export default {  data() {    return {      name: 'Flavio'    }  },  filters: {    fallback: function(name) {      return name ? name : 'there'    }  }}</script>

    Notice the syntax to apply a filter, which is | filterName. If you're familiar with Unix, that's the Unix pipe operator, which is used to pass the output of an operation as an input to the next one.

    Notice the syntax to apply a filter, which is | filterName . If you're familiar with Unix, that's the Unix pipe operator, which is used to pass the output of an operation as an input to the next one.

    The filters property of the component is an object. A single filter is a function that accepts a value and returns another value.

    The filters property of the component is an object. A single filter is a function that accepts a value and returns another value.

    The returned value is the one that’s actually printed in the Vue.js template.

    The returned value is the one that's actually printed in the Vue.js template.

    The filter, of course, has access to the component data and methods.

    The filter, of course, has access to the component data and methods.

    What’s a good use case for filters?

    What's a good use case for filters?

    • transforming a string, for example, capitalizing or making it lowercase

      transforming a string, for example, capitalizing or making it lowercase
    • formatting a price

      formatting a price

    Above you saw a simple example of a filter: {{ name | fallback }}.

    Above you saw a simple example of a filter: {{ name | fallback }} .

    Filters can be chained, by repeating the pipe syntax:

    Filters can be chained, by repeating the pipe syntax:

    {{ name | fallback | capitalize }}

    This first applies the fallback filter, then the capitalize filter (which we didn't define, but try making one!).

    This first applies the fallback filter, then the capitalize filter (which we didn't define, but try making one!).

    Advanced filters can also accept parameters, using the normal function parameters syntax:

    Advanced filters can also accept parameters, using the normal function parameters syntax:

    <template>  <p>Hello {{ name | prepend('Dr.') }}</p></template>
    <script>export default {  data() {    return {      name: 'House'    }  },  filters: {    prepend: (name, prefix) => {      return `${prefix} ${name}`    }  }}</script>

    If you pass parameters to a filter, the first one passed to the filter function is always the item in the template interpolation (name in this case), followed by the explicit parameters you passed.

    If you pass parameters to a filter, the first one passed to the filter function is always the item in the template interpolation ( name in this case), followed by the explicit parameters you passed.

    You can use multiple parameters by separating them using a comma.

    You can use multiple parameters by separating them using a comma.

    Notice I used an arrow function. We avoid arrow functions in methods and computed properties, generally, because they almost always reference this to access the component data. But in this case, the filter does not need to access this but receives all the data it needs through the parameters, and we can safely use the simpler arrow function syntax.

    Notice I used an arrow function. We avoid arrow functions in methods and computed properties, generally, because they almost always reference this to access the component data. But in this case, the filter does not need to access this but receives all the data it needs through the parameters, and we can safely use the simpler arrow function syntax.

    This package has a lot of pre-made filters for you to use directly in templates, which include capitalize, uppercase, lowercase, placeholder, truncate, currency, pluralize and more.

    This package has a lot of pre-made filters for you to use directly in templates, which include capitalize , uppercase , lowercase , placeholder , truncate , currency , pluralize and more.

    Communication among components (Communication among components)

    Components in Vue can communicate in various ways.

    Components in Vue can communicate in various ways.

    Using Props (Using Props)

    The first way is by using props.

    The first way is by using props.

    Parents “pass down” data by adding arguments to the component declaration:

    Parents “pass down” data by adding arguments to the component declaration:

    <template>  <div>    <Car color="green" />  </div></template>
    <script>import Car from './components/Car'
    export default {  name: 'App',  components: {    Car  }}</script>

    Props are one-way: from parent to child. Any time the parent changes the prop, the new value is sent to the child and re-rendered.

    Props are one-way: from parent to child. Any time the parent changes the prop, the new value is sent to the child and re-rendered.

    The reverse is not true, and you should never mutate a prop inside the child component.

    The reverse is not true, and you should never mutate a prop inside the child component.

    Using Events to communicate from children to parent (Using Events to communicate from children to parent)

    Events allow you to communicate from the children up to the parent:

    Events allow you to communicate from the children up to the parent:

    <script>export default {  name: 'Car',  methods: {    handleClick: function() {      this.$emit('clickedSomething')    }  }}</script>

    The parent can intercept this using the v-on directive when including the component in its template:

    The parent can intercept this using the v-on directive when including the component in its template:

    <template>  <div>    <Car v-on:clickedSomething="handleClickInParent" />    <!-- or -->    <Car @clickedSomething="handleClickInParent" />  </div></template>
    <script>export default {  name: 'App',  methods: {    handleClickInParent: function() {      //...    }  }}</script>

    You can pass parameters of course:

    You can pass parameters of course:

    <script>export default {  name: 'Car',  methods: {    handleClick: function() {      this.$emit('clickedSomething', param1, param2)    }  }}</script>

    and retrieve them from the parent:

    and retrieve them from the parent:

    <template>  <div>    <Car v-on:clickedSomething="handleClickInParent" />    <!-- or -->    <Car @clickedSomething="handleClickInParent" />  </div></template>
    <script>export default {  name: 'App',  methods: {    handleClickInParent: function(param1, param2) {      //...    }  }}</script>

    Using an Event Bus to communicate between any components (Using an Event Bus to communicate between any components)

    Using events you’re not limited to child-parent relationships. You can use the so-called Event Bus.

    Using events you're not limited to child-parent relationships. You can use the so-called Event Bus.

    Above we used this.$emit to emit an event on the component instance.

    Above we used this.$emit to emit an event on the component instance.

    What we can do instead is to emit the event on a more generally accessible component.

    What we can do instead is to emit the event on a more generally accessible component.

    this.$root, the root component, is commonly used for this.

    this.$root , the root component, is commonly used for this.

    You can also create a Vue component dedicated to this job, and import it where you need.

    You can also create a Vue component dedicated to this job, and import it where you need.

    <script>export default {  name: 'Car',  methods: {    handleClick: function() {      this.$root.$emit('clickedSomething')    }  }}</script>

    Any other component can listen for this event. You can do so in the mounted callback:

    Any other component can listen for this event. You can do so in the mounted callback:

    <script>export default {  name: 'App',  mounted() {    this.$root.$on('clickedSomething', () => {      //...    })  }}</script>

    This is what Vue provides out of the box.

    This is what Vue provides out of the box.

    When you outgrow this, you can look into Vuex or other 3rd part libraries.

    When you outgrow this, you can look into Vuex or other 3rd part libraries.

    Manage state using Vuex (Manage state using Vuex)

    Vuex is the official state management library for Vue.js.

    Vuex is the official state management library for Vue.js.

    Its job is to share data across the components of your application.

    Its job is to share data across the components of your application.

    Components in Vue.js out of the box can communicate using

    Components in Vue.js out of the box can communicate using

    • props, to pass state down to child components from a parent

      props, to pass state down to child components from a parent
    • events, to change the state of a parent component from a child, or using the root component as an event bus

      events, to change the state of a parent component from a child, or using the root component as an event bus

    Sometimes things get more complex than what these simple options allow.

    Sometimes things get more complex than what these simple options allow.

    In this case, a good option is to centralize the state in a single store. This is what Vuex does.

    In this case, a good option is to centralize the state in a single store. This is what Vuex does.

    Why should you use Vuex? (Why should you use Vuex?)

    Vuex is not the only state management option you can use in Vue (you can use Redux too), but its main advantage is that it’s official, and its integration with Vue.js is what makes it shine.

    Vuex is not the only state management option you can use in Vue (you can use Redux too), but its main advantage is that it's official, and its integration with Vue.js is what makes it shine.

    With React you have the trouble of having to choose one of the many libraries available, as the ecosystem is huge and has no actual standard. Lately Redux was the most popular choice, with MobX following up in terms of popularity. With Vue I’d go as far as to say that you won’t need to look around for anything other than Vuex, especially when starting out.

    With React you have the trouble of having to choose one of the many libraries available, as the ecosystem is huge and has no actual standard. Lately Redux was the most popular choice, with MobX following up in terms of popularity. With Vue I'd go as far as to say that you won't need to look around for anything other than Vuex, especially when starting out.

    Vuex borrowed many of its ideas from the React ecosystem, as this is the Flux pattern popularized by Redux.

    Vuex borrowed many of its ideas from the React ecosystem, as this is the Flux pattern popularized by Redux.

    If you know Flux or Redux already, Vuex will be very familiar. If you don’t, no problem — I’ll explain every concept from the ground up.

    If you know Flux or Redux already, Vuex will be very familiar. If you don't, no problem — I'll explain every concept from the ground up.

    Components in a Vue application can have their own state. For example, an input box will store the data entered into it locally. This is perfectly fine, and components can have local state even when using Vuex.

    Components in a Vue application can have their own state. For example, an input box will store the data entered into it locally. This is perfectly fine, and components can have local state even when using Vuex.

    You know that you need something like Vuex when you start doing a lot of work to pass a piece of state around.

    You know that you need something like Vuex when you start doing a lot of work to pass a piece of state around.

    In this case, Vuex provides a central repository store for the state, and you mutate the state by asking the store to do that.

    In this case, Vuex provides a central repository store for the state, and you mutate the state by asking the store to do that.

    Every component that depends on a particular piece of the state will access it using a getter on the store, which makes sure it’s updated as soon as that thing changes.

    Every component that depends on a particular piece of the state will access it using a getter on the store, which makes sure it's updated as soon as that thing changes.

    Using Vuex will introduce some complexity into the application, as things need to be set up in a certain way to work correctly. But if this helps solve the unorganized props passing and event system that might grow into a spaghetti mess if too complicated, then it’s a good choice.

    Using Vuex will introduce some complexity into the application, as things need to be set up in a certain way to work correctly. But if this helps solve the unorganized props passing and event system that might grow into a spaghetti mess if too complicated, then it's a good choice.

    开始吧 (Let’s start)

    In this example, I’m starting from a Vue CLI application. Vuex can be used also by directly loading it into a script tag. But, since Vuex is more in tune with bigger applications, it’s much more likely you will use it on a more structured application, like the ones you can start up quickly with the Vue CLI.

    In this example, I'm starting from a Vue CLI application. Vuex can be used also by directly loading it into a script tag. But, since Vuex is more in tune with bigger applications, it's much more likely you will use it on a more structured application, like the ones you can start up quickly with the Vue CLI.

    The examples I use will be put CodeSandbox, which is a great service that has a Vue CLI sample ready to go. I recommend using it to play around.

    The examples I use will be put CodeSandbox, which is a great service that has a Vue CLI sample ready to go. I recommend using it to play around.

    Once you’re there, click the Add dependency button, enter “vuex” and click it.

    Once you're there, click the Add dependency button, enter “vuex” and click it.

    Now Vuex will be listed in the project dependencies.

    Now Vuex will be listed in the project dependencies.

    To install Vuex locally you can simply run npm install vuex or yarn add vuex inside the project folder.

    To install Vuex locally you can simply run npm install vuex or yarn add vuex inside the project folder.

    Create the Vuex store (Create the Vuex store)

    Now we are ready to create our Vuex store.

    Now we are ready to create our Vuex store.

    This file can be put anywhere. It’s generally suggested to put it in the src/store/store.js file, so we'll do that.

    This file can be put anywhere. It's generally suggested to put it in the src/store/store.js file, so we'll do that.

    In this file we initialize Vuex and tell Vue to use it:

    In this file we initialize Vuex and tell Vue to use it:

    import Vue from 'vue'import Vuex from 'vuex'
    Vue.use(Vuex)
    export const store = new Vuex.Store({})

    We export a Vuex store object, which we create using the Vuex.Store() API.

    We export a Vuex store object, which we create using the Vuex.Store() API.

    A use case for the store (A use case for the store)

    Now that we have a skeleton in place, let’s come up with an idea for a good use case for Vuex, so I can introduce its concepts.

    Now that we have a skeleton in place, let's come up with an idea for a good use case for Vuex, so I can introduce its concepts.

    For example, I have two sibling components, one with an input field, and one that prints that input field content.

    For example, I have two sibling components, one with an input field, and one that prints that input field content.

    When the input field is changed, I want to also change the content in that second component. Very simple, but this will do the job for us.

    When the input field is changed, I want to also change the content in that second component. Very simple, but this will do the job for us.

    Introducing the new components we need (Introducing the new components we need)

    I delete the HelloWorld component and add a Form component, and a Display component.

    I delete the HelloWorld component and add a Form component, and a Display component.

    <template>  <div>    <label for="flavor">Favorite ice cream flavor?</label>    <input name="flavor">  </div></template>
    <template>  <div>    <p>You chose ???</p>  </div></template>

    Adding those components to the app (Adding those components to the app)

    We add them to the App.vue code instead of the HelloWorld component:

    We add them to the App.vue code instead of the HelloWorld component:

    <template>  <div id="app">    <Form/>    <Display/>  </div></template>
    <script>import Form from './components/Form'import Display from './components/Display'
    export default {  name: 'App',  components: {    Form,    Display  }}</script>

    Add the state to the store (Add the state to the store)

    So with this in place, we go back to the store.js file. We add a property to the store called state, which is an object, that contains the flavor property. That's an empty string initially.

    So with this in place, we go back to the store.js file. We add a property to the store called state , which is an object, that contains the flavor property. That's an empty string initially.

    import Vue from 'vue'import Vuex from 'vuex'
    Vue.use(Vuex)
    export const store = new Vuex.Store({  state: {    flavor: ''  }})

    We’ll update it when the user types into the input field.

    We'll update it when the user types into the input field.

    Add a mutation (Add a mutation)

    The state cannot be manipulated except by using mutations. We set up one mutation which will be used inside the Form component to notify the store that the state should change.

    The state cannot be manipulated except by using mutations. We set up one mutation which will be used inside the Form component to notify the store that the state should change.

    import Vue from 'vue'import Vuex from 'vuex'
    Vue.use(Vuex)
    export const store = new Vuex.Store({  state: {    flavor: ''  },  mutations: {    change(state, flavor) {      state.flavor = flavor    }  }})

    Add a getter to reference a state property (Add a getter to reference a state property)

    With that set, we need to add a way to look at the state. We do so using getters. We set up a getter for the flavorproperty:

    With that set, we need to add a way to look at the state. We do so using getters. We set up a getter for the flavor property:

    import Vue from 'vue'import Vuex from 'vuex'
    Vue.use(Vuex)
    export const store = new Vuex.Store({  state: {    flavor: ''  },  mutations: {    change(state, flavor) {      state.flavor = flavor    }  },  getters: {    flavor: state => state.flavor  }})

    Notice how getters is an object. flavor is a property of this object, which accepts the state as the parameter, and returns the flavor property of the state.

    Notice how getters is an object. flavor is a property of this object, which accepts the state as the parameter, and returns the flavor property of the state.

    Adding the Vuex store to the app (Adding the Vuex store to the app)

    Now the store is ready to be used. We go back to our application code, and in the main.js file, we need to import the state and make it available in our Vue app.

    Now the store is ready to be used. We go back to our application code, and in the main.js file, we need to import the state and make it available in our Vue app.

    We add

    We add

    import { store } from './store/store'

    and we add it to the Vue application:

    and we add it to the Vue application:

    new Vue({  el: '#app',  store,  components: { App },  template: '<App/>'})

    Once we add this, since this is the main Vue component, the store variable inside every Vue component will point to the Vuex store.

    Once we add this, since this is the main Vue component, the store variable inside every Vue component will point to the Vuex store.

    Update the state on a user action using commit (Update the state on a user action using commit)

    Let’s update the state when the user types something.

    Let's update the state when the user types something.

    We do so by using the store.commit() API.

    We do so by using the store.commit() API.

    But first, let’s create a method that is invoked when the input content changes. We use @input rather than @changebecause the latter is only triggered when the focus is moved away from the input box, while @input is called on every keypress.

    But first, let's create a method that is invoked when the input content changes. We use @input rather than @change because the latter is only triggered when the focus is moved away from the input box, while @input is called on every keypress.

    <template>  <div>    <label for="flavor">Favorite ice cream flavor?</label>    <input @input="changed" name="flavor">  </div></template>
    <script>export default {  methods: {    changed: function(event) {      alert(event.target.value)    }  }}</script>

    Now that we have the value of the flavor, we use the Vuex API:

    Now that we have the value of the flavor, we use the Vuex API:

    <script>export default {  methods: {    changed: function(event) {      this.$store.commit('change', event.target.value)    }  }}</script>

    See how we reference the store using this.$store? This is thanks to the inclusion of the store object in the main Vue component initialization.

    See how we reference the store using this.$store ? This is thanks to the inclusion of the store object in the main Vue component initialization.

    The commit() method accepts a mutation name (we used change in the Vuex store) and a payload, which will be passed to the mutation as the second parameter of its callback function.

    The commit() method accepts a mutation name (we used change in the Vuex store) and a payload, which will be passed to the mutation as the second parameter of its callback function.

    Use the getter to print the state value (Use the getter to print the state value)

    Now we need to reference the getter of this value in the Display template, by using $store.getters.flavor. this can be removed because we're in the template, and this is implicit.

    Now we need to reference the getter of this value in the Display template, by using $store.getters.flavor . this can be removed because we're in the template, and this is implicit.

    <template>  <div>    <p>You chose {{ $store.getters.flavor }}</p>  </div></template>

    The full, working source code is available here.

    The full, working source code is available here .

    There are still many concepts missing in this puzzle:

    There are still many concepts missing in this puzzle:

    • actions

      行动
    • modules

      模组
    • helpers

      helpers
    • plugins

      plugins

    But now you have the basics to go and read about them in the official docs.

    But now you have the basics to go and read about them in the official docs.

    Handle URLs using Vue Router (Handle URLs using Vue Router)

    In a JavaScript web application, a router is the part that syncs the currently displayed view with the browser address bar content.

    In a JavaScript web application, a router is the part that syncs the currently displayed view with the browser address bar content.

    In other words, it’s the part that makes the URL change when you click something in the page, and helps to show the correct view when you hit a specific URL.

    In other words, it's the part that makes the URL change when you click something in the page, and helps to show the correct view when you hit a specific URL.

    Traditionally, the Web is built around URLs. When you hit a certain URL, a specific page is displayed.

    Traditionally, the Web is built around URLs. When you hit a certain URL, a specific page is displayed.

    With the introduction of applications that run inside the browser and change what the user sees, many applications broke this interaction, and you had to manually update the URL with the browser’s History API.

    With the introduction of applications that run inside the browser and change what the user sees, many applications broke this interaction, and you had to manually update the URL with the browser's History API.

    You need a router when you need to sync URLs to views in your app. It’s a very common need, and all the major modern frameworks now allow you to manage routing.

    You need a router when you need to sync URLs to views in your app. It's a very common need, and all the major modern frameworks now allow you to manage routing.

    The Vue Router library is the way to go for Vue.js applications. Vue does not enforce the use of this library. You can use whatever generic routing library you want, or also create your own History API integration, but the benefit of using Vue Router is that it’s official.

    The Vue Router library is the way to go for Vue.js applications. Vue does not enforce the use of this library. You can use whatever generic routing library you want, or also create your own History API integration, but the benefit of using Vue Router is that it's official.

    This means it’s maintained by the same people who maintain Vue, so you get a more consistent integration in the framework, and the guarantee that it’s always going to be compatible in the future, no matter what.

    This means it's maintained by the same people who maintain Vue, so you get a more consistent integration in the framework, and the guarantee that it's always going to be compatible in the future, no matter what.

    安装 (Installation)

    Vue Router is available via npm with the package named vue-router.

    Vue Router is available via npm with the package named vue-router .

    If you use Vue via a script tag, you can include Vue Router using

    If you use Vue via a script tag, you can include Vue Router using

    <script src="https://unpkg.com/vue-router"></script>

    UNPKG is a very handy tool that makes every npm package available in the browser with a simple link.

    UNPKG is a very handy tool that makes every npm package available in the browser with a simple link.

    If you use the Vue CLI, install it using:

    If you use the Vue CLI, install it using:

    npm install vue-router

    Once you install vue-router and make it available either using a script tag or via Vue CLI, you can now import it in your app.

    Once you install vue-router and make it available either using a script tag or via Vue CLI, you can now import it in your app.

    You import it after vue, and you call Vue.use(VueRouter) to install it inside the app:

    You import it after vue , and you call Vue.use(VueRouter) to install it inside the app:

    import Vue from 'vue'import VueRouter from 'vue-router'
    Vue.use(VueRouter)

    After you call Vue.use() passing the router object, in any component of the app you have access to these objects:

    After you call Vue.use() passing the router object, in any component of the app you have access to these objects:

    • this.$router is the router object

      this.$router is the router object

    • this.$route is the current route object

      this.$route is the current route object

    The router object (The router object)

    The router object, accessed using this.$router from any component when the Vue Router is installed in the root Vue component, offers many nice features.

    The router object, accessed using this.$router from any component when the Vue Router is installed in the root Vue component, offers many nice features.

    We can make the app navigate to a new route using

    We can make the app navigate to a new route using

    • this.$router.push()

      this.$router.push()

    • this.$router.replace()

      this.$router.replace()

    • this.$router.go()

      this.$router.go()

    which resemble the pushState, replaceState and go methods of the History API.

    which resemble the pushState , replaceState and go methods of the History API.

    • push() is used to go to a new route, adding a new item to the browser history

      push() is used to go to a new route, adding a new item to the browser history

    • replace() is the same, except it does not push a new state to the history

      replace() is the same, except it does not push a new state to the history

    Usage samples:

    Usage samples:

    this.$router.push('about') //named route, see laterthis.$router.push({ path: 'about' })this.$router.push({ path: 'post', query: { post_slug: 'hello-world' } }) //using query parameters (post?post_slug=hello-world)this.$router.replace({ path: 'about' })

    go() goes back and forth, accepting a number that can be positive or negative to go back in the history:

    go() goes back and forth, accepting a number that can be positive or negative to go back in the history:

    this.$router.go(-1) //go back 1 stepthis.$router.go(1) //go forward 1 step

    Defining the routes (Defining the routes)

    I’m using a Vue Single File Component in this example.

    I'm using a Vue Single File Component in this example.

    In the template I use a nav tag that has three router-link components, which have the labels Home, Login, and About. A URL is assigned through the to attribute.

    In the template I use a nav tag that has three router-link components, which have the labels Home, Login, and About. A URL is assigned through the to attribute.

    The router-view component is where the Vue Router will put the content that matches the current URL.

    The router-view component is where the Vue Router will put the content that matches the current URL.

    <template>  <div id="app">    <nav>      <router-link to="/">Home</router-link>      <router-link to="/login">Login</router-link>      <router-link to="/about">About</router-link>    </nav>    <router-view></router-view>  </div></template>

    A router-link component renders an a tag by default (you can change that). Every time the route changes, either by clicking a link or by changing the URL, a router-link-active class is added to the element that refers to the active route, allowing you to style it.

    A router-link component renders an a tag by default (you can change that). Every time the route changes, either by clicking a link or by changing the URL, a router-link-active class is added to the element that refers to the active route, allowing you to style it.

    In the JavaScript part, we first include and install the router, then we define three route components.

    In the JavaScript part, we first include and install the router, then we define three route components.

    We pass them to the initialization of the router object, and we pass this object to the Vue root instance.

    We pass them to the initialization of the router object, and we pass this object to the Vue root instance.

    Here’s the code:

    这是代码:

    <script>import Vue from 'vue'import VueRouter from 'vue-router'
    Vue.use(Router)
    const Home  = {  template: '<div>Home</div>'}
    const Login = {  template: '<div>Login</div>'}
    const About = {  template: '<div>About</div>'}
    const router = new VueRouter({  routes: [    { path: '/', component: Home },    { path: '/login', component: Login },    { path: '/about', component: About }  ]})
    new Vue({  router}).$mount('#app')</script>

    Usually, in a Vue app, you instantiate and mount the root app using:

    Usually, in a Vue app, you instantiate and mount the root app using:

    new Vue({  render: h => h(App)}).$mount('#app')

    When using the Vue Router, you don’t pass a render property but instead, you use router.

    When using the Vue Router, you don't pass a render property but instead, you use router .

    The syntax used in the above example:

    The syntax used in the above example:

    new Vue({  router}).$mount('#app')

    is shorthand for:

    is shorthand for:

    new Vue({  router: router}).$mount('#app')

    See in the example, we pass a routes array to the VueRouter constructor. Each route in this array has a path and component params.

    See in the example, we pass a routes array to the VueRouter constructor. Each route in this array has a path and component params.

    If you pass a name param too, you have a named route.

    If you pass a name param too, you have a named route.

    Using named routes to pass parameters to the router push and replace methods (Using named routes to pass parameters to the router push and replace methods)

    Remember how we used the Router object to push a new state before?

    Remember how we used the Router object to push a new state before?

    this.$router.push({ path: 'about' })

    With a named route we can pass parameters to the new route:

    With a named route we can pass parameters to the new route:

    this.$router.push({ name: 'post', params: { post_slug: 'hello-world' } })

    The same goes for replace():

    The same goes for replace() :

    this.$router.replace({ name: 'post', params: { post_slug: 'hello-world' } })

    The application will render the route component that matches the URL passed to the link.

    The application will render the route component that matches the URL passed to the link.

    The new route component that handles the URL is instantiated and its guards called, and the old route component will be destroyed.

    The new route component that handles the URL is instantiated and its guards called, and the old route component will be destroyed.

    Route guards (Route guards)

    Since we mentioned guards, let’s introduce them.

    Since we mentioned guards, let's introduce them.

    You can think of them as life cycle hooks or middleware. Those are functions called at specific times during the execution of the application. You can jump in and alter the execution of a route, redirecting or simply canceling the request.

    You can think of them as life cycle hooks or middleware. Those are functions called at specific times during the execution of the application. You can jump in and alter the execution of a route, redirecting or simply canceling the request.

    You can have global guards by adding a callback to the beforeEach() and afterEach() property of the router.

    You can have global guards by adding a callback to the beforeEach() and afterEach() property of the router.

    • beforeEach() is called before the navigation is confirmed

      beforeEach() is called before the navigation is confirmed

    • beforeResolve() is called when beforeEach() is executed and all the components beforeRouterEnter and beforeRouteUpdate guards are called, but before the navigation is confirmed. The final check.

      beforeResolve() is called when beforeEach() is executed and all the components beforeRouterEnter and beforeRouteUpdate guards are called, but before the navigation is confirmed. The final check.

    • afterEach() is called after the navigation is confirmed

      afterEach() is called after the navigation is confirmed

    What does “the navigation is confirmed” mean? We’ll see it in a second. In the meantime think of it as “the app can go to that route”.

    What does “the navigation is confirmed” mean? We'll see it in a second. In the meantime think of it as “the app can go to that route”.

    The usage is:

    The usage is:

    this.$router.beforeEach((to, from, next) => {  // ...})
    this.$router.afterEach((to, from) => {  // ...})

    to and from represent the route objects that we go to and from.

    to and from represent the route objects that we go to and from.

    beforeEach has an additional parameter next which if we call with false as the parameter, will block the navigation and cause it to be unconfirmed.

    beforeEach has an additional parameter next which if we call with false as the parameter, will block the navigation and cause it to be unconfirmed.

    Like in Node middleware, if you're familiar, next() should always be called, otherwise execution will get stuck.

    Like in Node middleware, if you're familiar, next() should always be called, otherwise execution will get stuck.

    Single route components also have guards:

    Single route components also have guards:

    • beforeRouteEnter(from, to, next) is called before the current route is confirmed

      beforeRouteEnter(from, to, next) is called before the current route is confirmed

    • beforeRouteUpdate(from, to, next) is called when the route changes but the component that manages it is still the same (with dynamic routing, see next)

      beforeRouteUpdate(from, to, next) is called when the route changes but the component that manages it is still the same (with dynamic routing, see next )

    • beforeRouteLeave(from, to, next) is called when we move away from here

      beforeRouteLeave(from, to, next) is called when we move away from here

    We mentioned navigation. To determine if the navigation to a route is confirmed, Vue Router performs some checks:

    We mentioned navigation. To determine if the navigation to a route is confirmed, Vue Router performs some checks:

    • it calls beforeRouteLeave guard in the current component(s)

      it calls beforeRouteLeave guard in the current component(s)

    • it calls the router beforeEach() guard

      it calls the router beforeEach() guard

    • it calls the beforeRouteUpdate() in any component that needs to be reused, if any exist

      it calls the beforeRouteUpdate() in any component that needs to be reused, if any exist

    • it calls the beforeEnter() guard on the route object (I didn't mention it but you can look here)

      it calls the beforeEnter() guard on the route object (I didn't mention it but you can look here )

    • it calls the beforeRouterEnter() in the component that we should enter into

      it calls the beforeRouterEnter() in the component that we should enter into

    • it calls the router beforeResolve() guard

      it calls the router beforeResolve() guard

    • if all was fine, the navigation is confirmed!

      if all was fine, the navigation is confirmed!
    • it calls the router afterEach() guard

      it calls the router afterEach() guard

    You can use the route-specific guards (beforeRouteEnter and beforeRouteUpdate in case of dynamic routing) as life cycle hooks, so you can start data fetching requests for example.

    You can use the route-specific guards ( beforeRouteEnter and beforeRouteUpdate in case of dynamic routing) as life cycle hooks, so you can start data fetching requests for example.

    Dynamic routing (Dynamic routing)

    The example above shows a different view based on the URL, handling the /, /login and /about routes.

    The example above shows a different view based on the URL, handling the / , /login and /about routes.

    A very common need is to handle dynamic routes, like having all posts under /post/, each with the slug name:

    A very common need is to handle dynamic routes, like having all posts under /post/ , each with the slug name:

    • /post/first

      /post/first

    • /post/another-post

      /post/another-post

    • /post/hello-world

      /post/hello-world

    You can achieve this using a dynamic segment.

    You can achieve this using a dynamic segment.

    Those were static segments:

    Those were static segments:

    const router = new VueRouter({  routes: [    { path: '/', component: Home },    { path: '/login', component: Login },    { path: '/about', component: About }  ]})

    We add in a dynamic segment to handle blog posts:

    We add in a dynamic segment to handle blog posts:

    const router = new VueRouter({  routes: [    { path: '/', component: Home },    { path: '/post/:post_slug', component: Post },    { path: '/login', component: Login },    { path: '/about', component: About }  ]})

    Notice the :post_slug syntax. This means that you can use any string, and that will be mapped to the post_slugplaceholder.

    Notice the :post_slug syntax. This means that you can use any string, and that will be mapped to the post_slug placeholder.

    You’re not limited to this kind of syntax. Vue relies on this library to parse dynamic routes, and you can go wild with Regular Expressions.

    You're not limited to this kind of syntax. Vue relies on this library to parse dynamic routes, and you can go wild with Regular Expressions.

    Now inside the Post route component we can reference the route using $route, and the post slug using $route.params.post_slug:

    Now inside the Post route component we can reference the route using $route , and the post slug using $route.params.post_slug :

    const Post = {  template: '<div>Post: {{ $route.params.post_slug }}</div>'}

    We can use this parameter to load the contents from the back-end.

    We can use this parameter to load the contents from the back-end.

    You can have as many dynamic segments as you want, in the same URL:

    You can have as many dynamic segments as you want, in the same URL:

    /post/:author/:post_slug

    /post/:author/:post_slug

    Remember before when we talked about what happens when a user navigates to a new route?

    Remember before when we talked about what happens when a user navigates to a new route?

    In the case of dynamic routes, what happens is a little different.

    In the case of dynamic routes, what happens is a little different.

    For Vue to be more efficient, instead of destroying the current route component and re-instantiating it, it reuses the current instance.

    For Vue to be more efficient, instead of destroying the current route component and re-instantiating it, it reuses the current instance.

    When this happens, Vue calls the beforeRouteUpdate life cycle event.

    When this happens, Vue calls the beforeRouteUpdate life cycle event.

    There you can perform any operation you need:

    There you can perform any operation you need:

    const Post = {  template: '<div>Post: {{ $route.params.post_slug }}</div>'  beforeRouteUpdate(to, from, next) {    console.log(`Updating slug from ${from} to ${to}`)    next() //make sure you always call next()  }}

    Using props (Using props)

    In the examples, I used $route.params.* to access the route data. A component should not be so tightly coupled with the router, and instead, we can use props:

    In the examples, I used $route.params.* to access the route data. A component should not be so tightly coupled with the router, and instead, we can use props:

    const Post = {  props: ['post_slug'],  template: '<div>Post: {{ post_slug }}</div>'}
    const router = new VueRouter({  routes: [    { path: '/post/:post_slug', component: Post, props: true }  ]})

    Notice the props: true passed to the route object to enable this functionality.

    Notice the props: true passed to the route object to enable this functionality.

    Nested routes (Nested routes)

    Before I mentioned that you can have as many dynamic segments as you want, in the same URL, like:

    Before I mentioned that you can have as many dynamic segments as you want, in the same URL, like:

    /post/:author/:post_slug

    /post/:author/:post_slug

    So, say we have an Author component taking care of the first dynamic segment:

    So, say we have an Author component taking care of the first dynamic segment:

    <template>  <div id="app">    <router-view></router-view>  </div></template>
    <script>import Vue from 'vue'import VueRouter from 'vue-router'
    Vue.use(Router)
    const Author  = {  template: '<div>Author: {{ $route.params.author}}</div>'}
    const router = new VueRouter({  routes: [    { path: '/post/:author', component: Author }  ]})
    new Vue({  router}).$mount('#app')</script>

    We can insert a second router-view component instance inside the Author template:

    We can insert a second router-view component instance inside the Author template:

    const Author  = {  template: '<div>Author: {{ $route.params.author}}<router-view></router-view></div>'}

    We add the Post component:

    We add the Post component:

    const Post = {  template: '<div>Post: {{ $route.params.post_slug }}</div>'}

    Then we’ll inject the inner dynamic route in the VueRouter configuration:

    Then we'll inject the inner dynamic route in the VueRouter configuration:

    const router = new VueRouter({  routes: [{    path: '/post/:author',    component: Author,    children: [      path: ':post_slug',      component: Post    ]  }]})

    Thank you for reading!

    感谢您的阅读!

    Get this post PDF/ePub/Kindle ebook at vuehandbook.com

    Get this post PDF/ePub/Kindle ebook at vuehandbook.com

    翻译自: https://www.freecodecamp.org/news/the-vue-handbook-a-thorough-introduction-to-vue-js-1e86835d8446/

    vue.js手册

    展开全文
  • Vue.js 是用于构建交互式的 Web 界面的库。它提供了 MVVM 数据绑定和一个可组合的组件系统,具有简 单、灵活的 API。从技术上讲, Vue.js 集中在 MVVM 模式上的视图模型层,并通过双向数据绑定连接视图和模 型。实际...
  • Vue学习手册

    2019-02-26 17:24:14
    前端超热门的框架Vue,学习笔记,具体内容来自Vue官方文档
  • systemvue 用户手册

    2019-01-07 16:26:20
    安捷伦的systemvue用户手册,更方便新手上手systemvue
  • vue安装手册

    2018-10-31 11:18:43
    可以快速安装vue,包含配置的一些操作,可以把所需要安装的一系列东西按步骤操作即可
  • Vue2.0参考手册

    2017-09-19 12:35:31
    Vue2.0中文参考手册Vue中文参考手册Vuejs2.0中文参考手册Vue2.0中文参考手册Vue中文参考手册Vuejs2.0中文参考手册
  • vue2.0手册.zip

    2019-07-11 22:32:31
    vue官网的离线手册
  • vue2.0离线手册

    2018-12-24 14:43:08
    vue2.0离线手册
  • VUE学习手册

    2019-06-06 23:39:27
    VUE学习手册 环境搭建 1.首先需要在node.js的官网下载安装node环境,安装完后,windows环境打开CMD,输入node -v查看环境是否安装完毕。 2.然后执行npm -v,npm是node的一个包管理工具,查看npm是否已经安装完毕。 3...

    VUE学习手册

    环境搭建

    1.首先需要在node.js的官网下载安装node环境,安装完后,windows环境打开CMD,输入node -v查看环境是否安装完毕。
    2.然后执行npm -v,npm是node的一个包管理工具,查看npm是否已经安装完毕。
    3.下载vscode并下载相关插件,插件地址参考https://blog.csdn.net/Joe0217/article/details/80950477
    4.在CMD执行npm install --global vue-cli
    5.执行vue init webpack myproject
    

    标题命令行工具 (CLI)

    Vue 提供了一个官方的 CLI,为单页面应用 (SPA) 快速搭建繁杂的脚手架。它为现代前端工作流提供了 batteries-included 的构建设置。只需要几分钟的时间就可以运行起来并带有热重载、保存时 lint 校验,以及生产环境可用的构建版本。

    如何在VUE中使用less

    第一步 npm安装less
    npm install less less-loader --save
    第二步 修改webpack.base.conf.js文件,配置loader加载依赖,让其支持外部的less,在原来的代码上添加如下代码

    {
    test: /.less$/,
    loader: “style-loader!css-loader!less-loader”,
    },
    第三步 在组件中的style 添加lang=“less”

    VUE的优点

    • 解耦视图与数据
    • 可复用的组件
    • 前端路由
    • 状态管理
    • 虚拟DOM

    MVVM设计模式的优点

    1. 双向绑定技术,当Model变化时,View-Model会自动更新,View也会自动变化。很好的做到数据的一致性

    2. 由于控制器的功能大都移动到View上处理,大大的对控制器进行了瘦身

    3. View的功能进一步强化,具有控制的部分功能,

      若想无限增强它的功能,甚至控制器的全部功能几乎都可以迁移到各个View上

    (不过这样不可取,那样View干不了属于它职责范围内的事情)。

    View可以像控制器一样具有自己都View-Model

    1. 可以对View或ViewController的数据处理部分抽象出来一个函数处理model。

      这样它们专职页面布局和页面跳转,它们必然更一步的简化。

    MVVM设计模式的缺点

    1. 数据绑定也使得bug很难被调试。比如你看到页面异常了,有可能是你的View的代码有bug,也可能是你的model的代码有问题。数据绑定使得一个位置的Bug被快速传递到别的位置,要定位原始出问题的地方就变得不那么容易了。

    2. 数据双向绑定不利于代码重用。客户端开发最常用的是View,但是数据双向绑定技术,让你在一个View都绑定了一个model,不同的模块model都不同。那就不能简单重用view了

    3. 一个大的模块中model也会很大,虽然使用方便了也很容易保证数据的一致性,但是长期持有,不释放内存就造成话费更多的内存。

    VUE生命周期

    VUE生命周期
    在开始VUE生命周期时,首先要创建一个实例,也就是一个new vue()对象的过程,首先执行了init的方法,在init的过程中调用了beforecreat,实例创建完成后调用created,这个阶段完成了数据的观测,但是DOM元素还没有挂载,可以在这个阶段初始化一些数据。
    created完成后,vue会去判断instance(实例)里面是否有el选项,如果没有的话会调用vm.mount(el)templatetemplaterenderDOM,beforemountmount(el),然后执行下一步,如果有的话会直接执行下一步。 紧接着会判断是否有‘template’选项,如果有的话他会把template解析成一个render函数去构造虚拟DOM,在beforemount的时候,el还只是HTML里写的节点,当到了mounted的时候渲染的内容已经挂载到了DOM节点上,但是mounted不保证所有的DOM节点都会渲染完成,$nextTick函数可以保证所有的DOM已经完全渲染。
    后续的钩子函数执行的过程都是需要外部的触发才会执行。比如说有数据的变化,会调用beforeUpdate,然后经过Virtual DOM,最后updated更新完毕。当组件被销毁的时候,它会调用beforeDestory,以及destoryed。

    vue在观察到数据变化时并不是直接更新DOM,而是开启一个队列,并缓冲在同一事件循环中发生的所有变化。在缓冲时会去除重复数据,从而避免不必要的计算和DOM操作。
    如果你用for循环动态的改变一个数据100次,其实他只会应用最后一次的数据变化,如果没有这种机制,DOM就会重新绘制100次,这是一个很大的开销。

    Render函数

    VUE使用了虚拟DOM来更新DOM节点,提高渲染性能。
    虚拟DOM并不是真正意义上的DOM,而是一个JavaScript对象,在状态发生变化时,虚拟DOM会进行DIFF运算,来更新只需要被替换的DOM,而不是全部绘制。
    
    • 虚拟DOM就是通过一种VNode类来表达的,每个DOM元素或者组件都对应一个VNode对象
    • VNode分为文本节点,普通元素节点,组件节点,没有内容的注释节点,克隆节点
    • Render函数通过creatElement来创建虚拟DOM
    展开全文
  • vue常用手册

    2018-12-10 21:53:00
    1.搭建vue的开发环境: 1.必须要安装node.js 2.安装vue的脚手架工具 官方命令行工具 npm install --global vue-cli 3.新建项目 vue init webpack-simple gw 然后一直回车,新建完成后,cd到gw目录下,...

    1.搭建vue的开发环境:

    1.必须要安装node.js

    2.安装vue的脚手架工具 官方命令行工具

    npm install --global vue-cli

    3.新建项目

    vue init webpack-simple gw

    然后一直回车,新建完成后,cd到gw目录下,执行

    cnpm install

    4.运行项目

    npm run dev

    运行成功后,可以通过访问

    http://localhost:8080/

    2.vue路由

    vue路由的意思就是不用手动挂载组件,实现动态挂载的方式

    1.基础路由

      1. 安装vue-router

    cnpm install vue-router --save

    2.在src/main.js中

    import Vue from 'vue'
    import App from './App.vue'
    
    import VueRouter from 'vue-router';
    Vue.use(VueRouter);
    
    //1.创建组件
    import Home from './components/Home.vue';
    import New from './components/New.vue';
    
    //2.配置路由
    const routes=[
      {path:'/home',component:Home},
      {path:'/news',component:New},
      {path:'*',redirect:'/home'}
    ]
    
    //3.实例化VueRouter
    const router=new VueRouter({
      routes
    })
    
    //4.挂载路由
    new Vue({
      el: '#app',
      router,
      render: h => h(App)
    })
    
    //5.在根组件App.vue的模板中,放入<router-view></router-view>

     

    3.在src/App.vue中

    <template>
      <div id="app">
         <router-view></router-view>
      </div>
    </template>
    
    <script>
    export default {
      name: 'app',
      data () {
        return {
          msg:'你好'
        }
      }    
    }
    </script>
    <style>
    </style>

    4.重新运行项目,访问:

    http://localhost:8080/#/home
    http://localhost:8080/#/news

    即可看到两个组件被挂载了。

    2.路由跳转

    1.通过标签跳转

    1.在src/App.vue的模板中加入router-link

    <template>
      <div id="app">
          <router-link to="/home">首页</router-link>
         <router-link to="/news">新闻</router-link>
         
         <hr>
         <router-view></router-view>
         
      </div>
    </template>
    
    <script>
    export default {
      name: 'app',
      data () {
        return {
          msg:'你好'
        }
      }    
    }
    </script>
    <style>
    </style>

     2.通过js跳转

    1.在src/components/Home.vue中

    <template>
        <div>
            <h2>这是一个首页组件</h2>
            <v-header></v-header>
            <button @click="goNews()">通过js跳转到新闻页面</button>
        </div>
    </template>
    <script>
    export default {
        methods:{
            goNews(){
                this.$router.push({path:'/news'})
            }
        }
    }
    </script>
    <style>
    
    </style>

    3.父子路由

    1.在src/components目录下新建User.vue文件,同时再新建User目录,在User目录下新建UserAdd.vue和UserList.vue两个文件

    User.vue

    <template>
        <div id="user">
            <div class="user">
                <div class="left">
                    <ul>
                        <li>
                            
                            <router-link to="/user/useradd">增加用户</router-link>
                        </li>
                        <li>
                            
                            <router-link to="/user/userlist">用户列表</router-link>
                        </li>
                    </ul>
                </div>
                <div class="right">
                    <router-view></router-view>
                </div>
    
            </div>
            
        </div>
    </template>
    <script>
    export default {
        
    }
    </script>
    <style lang="scss" scoped>
        .user{
            display: flex;
            .left{
                width: 200px;
                min-height: 400px;
                border-right: 1px solid #eee
            }
            .right{
                flex: 1;
            }
        }
    </style>

    UserAdd.vue

    <template>
        <div id="adduser">
            用户增加
        </div>
    </template>

    UserList.vue

    <template>
        <div id="userlist">
            用户列表
        </div>
    </template>

    3.在src/main.js中

    import Vue from 'vue'
    import App from './App.vue'
    
    import VueRouter from 'vue-router';
    Vue.use(VueRouter);
    
    //1.创建组件
    import Home from './components/Home.vue';
    import New from './components/New.vue';
    import User from './components/User.vue';
      import UserAdd from './components/User/UserAdd.vue';
      import UserList from './components/User/UserList.vue';
    
    //2.配置路由
    const routes=[
      {path:'/home',component:Home},
      {path:'/news',component:New},
      {
        path:'/user',
        component:User,
        children:[
          {path:'useradd',component:UserAdd},
          {path:'userlist',component:UserList}
        ]
      },
      {path:'*',redirect:'/home'}
    ]
    
    //3.实例化VueRouter
    const router=new VueRouter({
      // mode:'history',
      routes
    })
    
    //4.挂载路由
    new Vue({
      el: '#app',
      router,
      render: h => h(App)
    })
    
    //5.在根组件App.vue的模板中,放入<router-view></router-view>

    4.路由模块化

    1.在src目录下新建router目录,router目录下新建router.js

    import Vue from 'vue'
    
    import VueRouter from 'vue-router';
    Vue.use(VueRouter);
    
    //1.创建组件
    import Home from '../components/Home.vue';
    import New from '../components/New.vue';
    import User from '../components/User.vue';
      import UserAdd from '../components/User/UserAdd.vue';
      import UserList from '../components/User/UserList.vue';
    
    //2.配置路由
    const routes=[
      {path:'/home',component:Home},
      {path:'/news',component:New},
      {
        path:'/user',
        component:User,
        children:[
          {path:'useradd',component:UserAdd},
          {path:'userlist',component:UserList}
        ]
      },
      {path:'*',redirect:'/home'}
    ]
    
    //3.实例化VueRouter
    const router=new VueRouter({
      // mode:'history',
      routes
    })
    
    export default router;
    
    //5.在根组件App.vue的模板中,放入<router-view></router-view>

    2.在src/main.js中

    import Vue from 'vue'
    import App from './App.vue'
    
    import router from './router/router.js';
    
    //4.挂载路由
    new Vue({
      el: '#app',
      router,
      render: h => h(App)
    })

     

    3.element UI的使用

    官网

    http://element-cn.eleme.io/#/zh-CN/component/installation

     

    1.安装

    cnpm i element-ui -S  //-S表示 --save

    2.将配置代码引入main.js中

    配置代码:

    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    
    Vue.use(ElementUI);

    main.js

    import Vue from 'vue'
    import App from './App.vue'
    
    
    //elementsUI 的使用
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    
    Vue.use(ElementUI);
    
    
    
    
    import VueRouter from 'vue-router';
    Vue.use(VueRouter);
    
    //1.创建组件
    import Home from './components/Home.vue';
    import New from './components/New.vue';
    import User from './components/User.vue';
      import UserAdd from './components/User/UserAdd.vue';
      import UserList from './components/User/UserList.vue';
    
    //2.配置路由
    const routes=[
      {path:'/home',component:Home},
      {path:'/news',component:New},
      {
        path:'/user',
        component:User,
        children:[
          {path:'useradd',component:UserAdd},
          {path:'userlist',component:UserList}
        ]
      },
      {path:'*',redirect:'/home'}
    ]
    
    //3.实例化VueRouter
    const router=new VueRouter({
      // mode:'history',
      routes
    })
    
    //4.挂载路由
    new Vue({
      el: '#app',
      router,
      render: h => h(App)
    })
    
    //5.在根组件App.vue的模板中,放入<router-view></router-view>
    View Code

     

    3.配置webpack.config.js,加入字体配置代码

    配置代码

    {
            test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
            loader: 'file-loader'
          },

    webpack.config.js

    var path = require('path')
    var webpack = require('webpack')
    
    module.exports = {
      entry: './src/main.js',
      output: {
        path: path.resolve(__dirname, './dist'),
        publicPath: '/dist/',
        filename: 'build.js'
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'vue-style-loader',
              'css-loader'
            ],
          },      {
            test: /\.vue$/,
            loader: 'vue-loader',
            options: {
              loaders: {
              }
              // other vue-loader options go here
            }
          },
          {
            test: /\.js$/,
            loader: 'babel-loader',
            exclude: /node_modules/
          },
          {
            test: /\.(png|jpg|gif|svg)$/,
            loader: 'file-loader',
            options: {
              name: '[name].[ext]?[hash]'
            }
          },
          {
            test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
            loader: 'file-loader'
          }
    
        ]
      },
      resolve: {
        alias: {
          'vue$': 'vue/dist/vue.esm.js'
        },
        extensions: ['*', '.js', '.vue', '.json']
      },
      devServer: {
        historyApiFallback: true,
        noInfo: true,
        overlay: true
      },
      performance: {
        hints: false
      },
      devtool: '#eval-source-map'
    }
    
    if (process.env.NODE_ENV === 'production') {
      module.exports.devtool = '#source-map'
      // http://vue-loader.vuejs.org/en/workflow/production.html
      module.exports.plugins = (module.exports.plugins || []).concat([
        new webpack.DefinePlugin({
          'process.env': {
            NODE_ENV: '"production"'
          }
        }),
        new webpack.optimize.UglifyJsPlugin({
          sourceMap: true,
          compress: {
            warnings: false
          }
        }),
        new webpack.LoaderOptionsPlugin({
          minimize: true
        })
      ])
    }
    View Code

    然后重启项目,发现不报错了。

     

     4.vuex

    vuex是一个专门为vue.js应用程序开发的状态管理模式,解决不同组件之间的同一状态共享问题,数据共享问题,数据持久化

    1.安装

    cnpm install vuex --save

    2.在src目录下新建目录vuex,在vuex目录下新建store.js文件

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex);
    
    // 1.state在vuex中用于储存数据
    var state={
        count:1
    }
    
    // 2.mutations里面放的是方法,方法主要内容用于改变state里面的数据
    var mutations={
        incCount(){
            ++state.count
        }
    }
    
    // 实例化Vuex.store
    const store=new Vuex.Store({
        state,
        mutations:mutations
    })
    
    export default store;

    3.在src/components/Home.vue中使用

    <template>
        <div>
            <h2>这是一个首页组件</h2>
            <button @click="goNews()">通过js跳转到新闻页面</button>
            <!-- 3.使用 -->
            <h2>全局变量--{{this.$store.state.count}}</h2>
            <h2>{{this.i}}</h2>
            <button @click="addcount()">增加数量+</button>
        </div>
    </template>
    <script>
    // 1.引入store
    import store from '../vuex/store.js';
    // 2.注册
    export default {
        store,
        methods:{
            goNews(){
                this.$router.push({path:'/news'})
            },
    
            addcount(){
                // 改变vuex.store里面的数据
                
                this.$store.commit('incCount');
            }
        },
        data(){
            return{
                i:0
            }
        },
        mounted(){
            this.i=this.$store.state.count
        }
    }
    </script>
    <style>
    
    </style>

     

     5.使用iview

    官网

    https://www.iviewui.com/docs/guide/install

    1.安装

    cnpm install  iview  --save

    2.在src/main.js加入

    import iView from 'iview'
    import 'iview/dist/styles/iview.css'    // 使用 CSS
    Vue.use(iView)

    3.配置webpack.config.js,加入字体配置代码

    配置代码

    {
            test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
            loader: 'file-loader'
          },

    webpack.config.js

    View Code

    然后重启项目,发现不报错了。

     

     

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    转载于:https://www.cnblogs.com/xuepangzi/p/10091136.html

    展开全文
  • Vue实用手册

    2019-01-25 17:31:29
    1.Vue.js-是国内开发者尤雨溪开发的js框架,它是实现UI层的渐进式框架, Vue借鉴了Angular的指令、React中组件和props等优点进行设计,从最简单的数据处理,到数据交互,到DOM操作,到路由处理等,VueJS都有完整的...

    1. Vue.js-是国内开发者尤雨溪开发的js框架,它是实现UI层的渐进式框架, Vue借鉴了Angular的指令、React中组件和props等优点进行设计,从最简单的数据处理,到数据交互,到DOM操作,到路由处理等,VueJS都有完整的解决方案。

     

    2. 两种开发模式

    (1). 直接引入vue.js文件即可

    (2). vue-cli

    ①. 确保电脑上装有NodeJS 4.0以上的版本,在CMD里面运行node –v查看版本

    ②. 全局安装 vue-cl

    在命令行输入:$ npm install --global vue-cli,全局安装vue-cli

    默认是从国外服务器下,可以使用阿里巴巴在国内的镜像服务器,通过config命令设置默认下载路径:npm config set registry https://registry.npm.taobao.org 

    然后再执行:npm install --global vue-cli,这样安装的速度会快一些,完成后,检查是否安装成功:vue -V (在此注意V为大写)

    ③. 创建一个基于 webpack 模板的新项目(名为my-project)

    在命令行输入:vue init webpack my-project,注意项目名不能有大写

    项目建立过程中,有如下选择,选择NO,该选项为使用ESLint规范你的代码,一个空格错误都将报错,不开启,避免不必要的麻烦,后两项为单元测试,可以选择No

    项目建立完成后,目录结构如下:

    ④. 安装依赖

    A. cd my-project 进入项目中

    B. npm install 安装依赖文件

    完成后,会发现项目目录下多出一个node_modules文件夹,里面就是 vue-cli 创建的一个基于 webpack 的 vue.js 项目,进入项目目录文件夹(my-project)中,就可以使用vue进行开发啦

    C. npm run dev,便可以打开本地服务器实时查看效果(localhost:8080)

    如果浏览器打开之后,没有加载出页面,有可能是本地的 8080 端口被占用,需要修改一下配置文件 config>index.js

    建议将端口号改为不常用的端口,另外我还将 build 的路径前缀修改为 ' ./ '(原本为 ' / '),是因为打包之后,外部引入 js 和 css 文件时,如果路径以 ' / ' 开头,在本地是无法找到对应文件的(服务器上没问题),所以如果需要在本地打开打包后的文件,就得修改文件路径

    npm run dev后的初始效果

    退出监听,可以直接Ctrl+C,选择Y

     

    3. Vue常用的属性

    (1). el  作用域(一般为顶层容器的id)

    (2). data  绑定的数据

    (3). props 接收父组件传递的参数

    (4). methods  方法

    (5). components 组件

    (6). directives 自定义指令

    (7). filters 过滤属性

    (8). computed 计算属性

    (9). watch  监听属性

    (10). 生命周期属性

    ①. beforeCreate 创建前

    ②. created  创建后 (常用于发起数据请求)

    ③. beforeMount 挂载前

    ④. mounted挂载后 (常用于发起数据请求)

    ⑤. beforeUpdate 更新前

    ⑥. updated 更新后

    ⑦. beforeDestroy 摧毁前

    ⑧. destroyed 摧毁后

     

    4. Vue常用的指令

    (1). 条件判断指令

    A. v-if   条件成立时挂载并显示

    B. v-else-if  紧跟v-if之后 , v-if不成立时,判断当前选项是否满足条件与显示

    C. v-else   紧跟v-if或v-else-if之后,前面的条件不成立时,挂载并显示

    最终解析如下:

    (2). v-for  循环指令 , 循环遍历当前选项所对应的数组或是对象

    最终解析如下:

    (3). v-show  显示指令,根据条件判断当前选项在DOM树上显示还是隐藏

    最终解析如下:

    (4). v-bind  绑定属性,缩写的形式: v-bind:src可以写成 :src

    在vue中 绑定html属性,必须使用v-bind

    最终解析如下:

    v-bind的属生可以和标签原有的属性同时存在

    可以直接绑定一个数组

    可以在绑定的数组中添加对象

    (5). v-model  双向数据绑定,此命令绑定的变量的值改变时,其他地方渲染这个变量的值也会同步发生改变。

    ①. v-model. lazy   延迟(确认后)更新

    ②. v-model. number   自动将用户的输入值转为 Number 类型

    ③. v-model. trim  自动过滤用户输入的首尾空格

    当input输入框在输入时,所对应的p标签里的值也会发生改变,最终解析如下:

    (6). v-on  绑定事件,缩写形式:v-on:click可以写成@click

    ①. v-on:click=" "  单击事件

    ②. v-on:click.once=" " 只可点击一次

    ③. v-on:click.top=" " 阻止事件冒泡

    ④. v-on:click.prevent=" " 阻止默认事件

    ⑤. v-on:dblclick=" " 双击事件

    ⑥. v-on:keydown.enter=" " 键盘按下事件,只对指定的按键号有效

    ⑦. v-on:keyup.13=" " 键盘弹起事件,只对指定的按键号有效

    (7)v-text 将内容按文本解析

    最终,页面的内容会按如下方式去渲染

    (8)v-html 将内容按html解析

    最终,页面的内容会按如下方式去渲染

    (9)v-cloak  优化加载闪烁

    这个指令在渲染时会自动去掉 ,可以将具有该属性的元素初始状态不显示,等到渲染到该属性后才显示,以实现读到取数据后才加载。

     

    5. directives 自定义指令

    (1). bind:只调用一次,指令第一次绑定到元素时调用

    (2). update:所在组件的 VNode 更新时调用

    (3). unbind: 只调用一次, 指令与元素解绑时调用

     

    6. filters 过滤属性

    用于数据的处理,与ng一样,通过 | 管道符号,支持多重过滤,而且支持给过滤器传参,过滤器的本质就是一个函数,自从Vue2.0之后,就已经自带的过滤取消,不再支持,用户要想使用,有两种方法:

    ①. https://github.com/wy-ei/vue-filter

    ②. 自定义过滤器

    A. 创建,在Vue实例的filters属性中指定

    B. 使用,依然是管道符号,只有传参方式变了:{{ price | currency('¥','@')}}

     

    7. computed 计算属性

    计算属性其实是一个方法,定义在computed属性中的方法,计算属性的优势:

    (1). 计算属性的方法和methods中的方法实现的功能是一样的,正常情况,在methods定义方法也是可以的,但是由于方法所依赖的数据,性能开销比较大,就适合用计算属性, 计算属性是有计算缓存的,可以让更新更高效

    (2). 让代码更方便进行维护

     

    8. watch  监听属性

    记录原数据,当数据更新时,会自动与原有数据进行对比

     

    9. components 组件

    组件在vue中使用的非常普遍,它可以将一些公共的部分抽离出来,随处调用,通过传入不同的参数从而展现不同的数据,这也是vue所谓渐进式框架的精髓,在结合脚手架的开发模式中,几乎所有的页面都是一个组件,下面来看一下如何定义组件与使用组件。

    定义子组件Header

    在父组件Home中使用子组件Header

     

    10. 组件之间的通信

    (1). 父组件给子组件传值 props

    ①. 在父组件里调用子组件时指定属性,把要传递的值赋给属性

    ②. 在子组件内部声明props,并在props里声明接收参数的属性,这样就可以通过props拿到传递过来的数据

    注意事项:

    ①. 在组件中,data属性必须是带有返回值,而且返回值是对象的方法

    ②. 如果在通过属性传值时,值是会变化,通过v-bind指令将变量绑定到属性

    定义子组件Header并规定所接受的参数

    在父组件Home里调用子组件Header并传参数

    (2). 子组件向父组件传值 $emit()

    ①. 在调用子组件时通过v-on与@绑定自定义的事件的名称

    ②. 在子组件中传参给父组件时通过调用$emit,传递两个参数,一个为自定义的事件名称,一个为通过事件传递的数据

    定义子组件Header并声明点击事件传递参数给父组件

    在父组件Home里接收子组件Header传递过来的参数

    (3). 父组件获取子组件的数据或方法:$refs

    ①. 在父组件件中调用子组件时通过 ref 为子组件指定一个名称

    ②. 在父组件件中通过 $refs 调用子组件数据或方法

    定义子组件Header

    在父组件Home中调用子组件Header,为它指定ref名称myHeader,在方法里通过this.$refs.myHeader获取Header的数据和方法

    (4). 子组件获取父组件的数据或方法:$parent

    ①. 在子组件中通过 $parent 调用父组件的数据或方法

    定义子组件Header

    在父组件Home中定义子组件想要的数据,让子组件获取

    (5). 兄弟组件之间通信,定义事件总线 eventBus

    ①. 定义一个公共事件总线 var eventBus = new Vue(),完成事件的触发和绑定

    ②. 在第一个组件中引入事件总线,传参时eventBus.$emit('事件名','参数')

    ③. 在第二个组件中引入事件总线,在生命周期钩子函数中监听eventBus.$on('事件名','function(){…...}')

    定义事件总线

    在第一个组件中引入事件总线,通过事件传参

    在第二个组件中引入事件总线,通过事件接收参数

     

    11. 组件分发内容slot

    (1). 单个slot

    子组件模板至少包含一个 <slot> 插口,否则调用子组件时,子组件内所分发的内容将会被丢弃

    当子组件模板只有一个没有属性的 slot 时,父组件整个内容片段将插入到 slot 所在的 DOM 位置,并替换掉 slot 标签本身

    最初在 <slot> 标签中的任何内容都被视为备用内容,备用内容在子组件的作用域内编译,并且只有在调用子组件时,组件标签内没有要分发的内容时才显示备用内容

    定义子组件son,在组件内预留插槽slot

    在父组件里调用子组件,在子组件里分发内容

    最终显示效果如下:

    (2). 具名slot

    slot元素可以用一个特殊的属性 name 来配置如何分发内容,多个 slot 可以有不同的名字,具名 slot 将匹配内容片段中有对应 slot 特性的元素

    仍然可以有一个匿名 slot,它是默认 slot,作为找不到匹配的内容片段的备用插槽,如果没有默认的 slot,这些找不到匹配的内容片段将被抛弃

    定义子组件son,在组件内添加slot,为slot指定name属性.

    在父组件里调用子组件,在子组件里分发内容,为内容指定slot属性值

    最终显示效果如下:

     

    12. 动态组件is

    通过使用预留的 <component> 元素,动态地绑定到它的 is 属性值,我们让多个组件可以使用同一个挂载点,并动态切换

     

    13. 路由配置

    (1). 引入vue及路由中间件并使用

    (2). 引入所有页面组件

    (3). 配置路由词典

    (4). 导出路由配置

    (5). 在main.js里导入配置的路由辞典、挂载使用

    (6). 在app.vue里使用router-view渲染配置的路由组件

     

    14. 路由跳转

    (1). 第一种方法:指定 router-link 与 router-view,进行跳转

    (2). 第二种方法:使用JS进行跳转  this.$router.push('/myLogin')

    (3). 第三种方法:使用a标签进行跳转,a href='#/myLogin'

     

    15. 路由传参

    (1). 配置接收方(main)的路由

    {  path:'/product/:id',  component:product , meta: ['推广素材'] }

    (2). 传参方式

    ①. href='#/product/123'

    ②. router-link to='/product/123'

    ③. router-link to='/product?id=123'(get传参)

    ④. this.$router.push('/product/123')

    ⑤. this.$router.push({ name:'xxx' params:{ id:id } })

    ⑥. this.$router.push({ path:'/xxx' query:{ id:id } })(get传参)

    注意:params传参,push里面只能是 name:'xxxx',不能是path:'/xxx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!

    (3). 获取参数

    ①. this.$route.query.id (get传参数获取)

    ②. this.$route.params.id (post传参数获取)

     

    16. 网络请求

    (1). 安装axios插件,然后在main.js里引入,并将其添加为Vue的原型方法

    (2). 页面请求,以POST请求为例,注意下面的添加参数方法。

    关于对axios请求的的封装可以查看本博客中的  Vue中封装axios请求方法 ,此处不再详细介绍。

     

    17. 状态管理Vuex

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化,如果需要构建是一个中大型单页应用,就需要考虑如何更好地在组件外部管理状态,Vuex 将会成为自然而然的选择,下面介绍一下Vuex的用法。

    第一步:创建store

    (1). 在页面文件中新建一个store.js文件,引入vue和vuex,并声明使明vuex。

    (2). 在store.js里声明state,用来存放组件之间共享的数据。

    如果页面的数据较多的时候可以在另外一个文件保存数据,然后在store.js里引入。

    (3). 在store.js里声明getters,有点类似于计算属性,改变state里的数据的时候会触发getters里的方法,获取新数据。

    有时候,我们需要对state的数据进行筛选或过滤,这些操作都是在组件的计算属性进行的, 如果多个组件需要用到筛选后的数据,那我们就必须到处重复写该计算属性函数;或者将其提取到一个公共的工具函数中,并将公共函数多处导入 ,这两种方法都不太理想,但是如果把数据筛选完在传到计算属性里就不用那么麻烦了,getters就是用来干这个的,getters下的函数接收接收state作为第一个参数。

    (4). 在store.js里声明mutations,主要用来存放方法,这些方法用于改变state里的数据。

    mutations下的函数接收state作为参数,接收payload(载荷)作为第二个参数,这个参数用来记录开发者使用该函数的传递的信息,以便用这些信息作为参数和依据改变state,需要注意的是:mutations方法必须是同步方法。

    (5). 在store.js里声明actions,用于异步改变state里的数据。

    actions和mutations的区别

    (1). actions 提交的是 mutations,而不是直接变更状态。也就是说,actions会通过commit提交mutations,让mutations帮他提交数据的变更。

    (2). action 可以包含任意异步操作,ajax、setTimeout、setInterval均可以操作。
     

    第二步:引入store

    第三步:使用store

     

    如果希望可以简化写法,还可以使用vuex的辅助函数,matState、、mapGetters、mapAcions、mapMutations来映射和操作数据。

     

     

    展开全文
  • vue 常用手册

    千次阅读 2018-07-16 17:10:38
    引入vue.js 创建Vue对象, 指定选项对象 el : 指定dom标签容器的选择器 data : 指定初始化状态属性数据的对象 对象/函数(返回一个对象) 页面中 使用v-model: 实现双向数据绑定 使用{{}} ; 显示...
  • Vue修炼手册 Day01

    千次阅读 2021-04-26 19:22:15
    Vue修炼手册第一章1. 什么是Vue2. Vue快速入门2.1 Hello Vue2.2 Vue中的el挂载点2.3 Vue中的data数据区3. Vue的指令3.1 什么是Vue指令3.2 Vue常用指令 1. 什么是Vue Vue.js(读音 /vjuː/, 类似于 view) 是一套构建...
  • E-ON_VUE使用手册_大气编辑器:比较全面的介绍了大气编辑器中的各个参数。对学习VUE很有帮助。
  • vue3.0手册

    2020-08-27 10:00:49
    https://www.bookstack.cn/read/vuejs-3.0.0-rc.1/9b7f4f6cd19444ae.md 全英文,慢慢啃,还是可以的
  • Vue修炼手册 Day02

    2021-04-28 22:07:01
    Vue修炼手册第二章1. Vue的网络数据操作1.1 axios的使用1.2 axios应用的Demo2. Vue的布局2.1 ElementUI的引入2.2 ElementUI的简单使用3. Node.js npm Vue-cli3.1 什么是Node.js、npm和Vue-cli3.2 安装Node.js3.3 ...
  • Vue修炼手册 Day03

    2021-05-05 10:47:58
    Vue修炼手册第三章Vue+ElementUI+SpringBoot的简单登录案例1 设计登录页面1.1 创建一个登录页面1.2 登录表单校验2 后台搭建2.1 创建Maven工程引入依赖2.2 使用MybatisPlus的代码生成器2.3 书写配置类2.4 业务层代码...
  • Vue 2 技术参考手册

    2019-12-06 16:40:00
    Vue 2 技术参考手册
  • Vue入门手册整理

    2019-03-18 22:20:00
    目录 第一章、环境搭建 第二章、目录结构 第三章、Vue调试 第四章、定义页面 附录资料 第一章、环境搭建 1.1、准备: npm: 6.9.0 (npm > 3.0) node: v10.15.3 (node > 6.11.5) vue...
  • vue2.0中文手册API

    2017-05-25 14:21:31
    vue2.0中文手册API,离线资源
  • vue2.0中文使用手册

    2018-09-06 09:25:43
    vue2.0中文使用手册
  • Vue 练习手册及答案

    2020-09-20 19:02:26
    Vue练习手册及答案 1、简述MVVM和MVC (1)MVC:是后台的框架模式 分为M:(model模型)、V(view试图)、C(controller控制器) (2)MVVM是为了实现MVC中的V MVVM分为:M(model数据)、V(view试图)、VM...
  • CISSP VUE机考报名手册

    2014-02-10 10:35:50
    CISSP VUE机考报名手册
  • Vue修炼手册 Day04

    2021-05-07 10:27:29
    Vue修炼手册第四章1. 完善退出功能1.1 登出过滤器1.2 在Shiro配置类中使用自定义过滤器2. 根据权限动态获取菜单2.1 后台接口2.2 前台页面动态生成菜单 继续完善Day03的Demo Day03 1. 完善退出功能 之前登出更能写完...
  • vue快速入门手册

    2019-10-08 16:02:50
    搭建Vue 安装脚手架工具npm install -g @vue/cli 创建项目vue create hello-world,hello-world为项目名称Babel、Vuex、Router,需要把着三个最基本选中 Vue技术栈:Vuex、Router 基本用法 关键字{{}},<p>{{...
  • Vue-router参考手册

    2018-04-28 15:13:17
    Vue-router参考手册,离线文档,有需要的可以下载,谢谢!
  • mongoVue操作手册

    千次阅读 2013-03-13 09:30:01
    转自:... MongoDB的客户端工具MongoVue,地址是http://www.mongovue.com/。 也可以通过后面网址下载:http://download.csdn.net/detail/shiyuezhong/4553444 1.0版之后超过15天后功
  • vue 速查手册

    2019-09-24 09:43:22
    一、vue指令 1、v-html 2、v-bind(可缩写为冒号 :) 3、v-show 4、v-if 5、v-on(可缩写为@) 6、v-for 二、表单 1、v-mode 修饰符 2、文本框 3、复选框 4、单选框 5、下拉框 三、vue 组件 1、全局组件 ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 919
精华内容 367
关键字:

vue手册

vue 订阅