01 Vue介绍

2023-12-16 20:27:30

概述

Developers in the industry must resolve frontend development problems quickly with minimal impact on existing workflows or backend architecture. In any cases, developers tend to overlook the UI until the end of a project, which can happen because of a lack of resources, ever-evolving product equirements, or the existing attitude that the frontend is the easy bit.

业内的开发人员必须快速解决前端开发问题,同时尽量减少对现有工作流程或后端架构的影响。在任何情况下,开发人员都倾向于在项目结束前忽略用户界面,这可能是由于缺乏资源、产品要求不断变化,或者认为前端是最简单的部分。

However, companies such as Apple and Google have proven that thinking through the design of the frontend is key to a solid product or platform that will excite and engage users, leading to a higher return on investment and a more successful business.

然而,苹果和谷歌等公司已经证明,对前端设计进行深入思考,是打造稳固的产品或平台的关键所在,它能激发和吸引用户,从而带来更高的投资回报和更成功的业务。

If you know Vue, you may have also come across other frontend frameworks that, at face value, solve the same problems, such as Ember, Angular, or React. At a surface level, they attempt to make reactive frontend development more reliable and introduce patterns that make it easier. However, there are significant differences in how a Vue project might play out compared to an Angular or React project. Let’s investigate them.

如果你了解 Vue,你可能还接触过其他前端框架,从表面上看,它们解决了同样的问题,如 Ember、Angular 或 React。从表面上看,它们都试图让反应式前端开发更可靠,并引入模式使其更简单。然而,与 Angular 或 React 项目相比,Vue 项目的运行方式有很大不同。让我们来研究一下。

比较Angular和Vue

Angular is a Model-View-ViewModel (MVVM) framework built by Google and has built-in support for TypeScript. The Angular ecosystem includes Ahead-of-Time (AoT) rendering, a router, and a CLI tool.

Angular 是由 Google 构建的模型-视图-视图模型(MVVM)框架,内置了对 TypeScript 的支持。Angular 生态系统包括超前(AoT)渲染、路由器和 CLI 工具。

However, it fails to deliver a simplified system for global state management; developers would need to learn how to use Flux or adopt NgRx.

但是,它无法为全局状态管理提供一个简化的系统;开发人员需要学习如何使用 Flux 或采用 NgRx。

Vue takes Angular’s core robustness and provides a better development experience by removing the restriction of an enforced code style for developers.

Vue 继承了 Angular 的核心稳健性,为开发人员消除了强制代码风格的限制,提供了更好的开发体验。

Vue also simplifies common Angular patterns, such as HTML directives, and eliminates a variety of Angular’s project structures, such as injectables, components, pipes, modules, and so on. From Vue 3.0 onward, it provides excellent support for TypeScript and typing without the drawbacks of Angular-enforced coding styles.

Vue 还简化了常见的 Angular 模式,如 HTML 指令,并消除了 Angular 的各种项目结构,如注入式、组件、管道、模块等。从 Vue 3.0 开始,它为 TypeScript 和类型化提供了出色的支持,而没有 Angular 强制编码风格的缺点。

Vue is more flexible, developer-friendly, efficient, and straightforward to set up and learn to use than Angular in many cases.

在许多情况下,Vue 比 Angular 更灵活、对开发人员更友好、更高效、更易于设置和学习使用。

Next, let’s look at how Vue and React differ.

接下来,让我们看看 Vue 和 React 有何不同。

比较React和Vue

First released in 2013 and backed by Meta (previously known as Facebook), React rapidly gained popularity in the developer community. React introduces the JSX pattern to write HTML syntax directly with JavaScript.

React 于 2013 年首次发布,并得到了 Meta(前身为 Facebook)的支持,迅速在开发人员社区中流行起来。React 引入了 JSX 模式,可直接使用 JavaScript 编写 HTML 语法。

With JSX, React increases the amount that new developers are required to learn about both JavaScript and component-based architecture.

通过 JSX,React 增加了新开发人员需要学习的 JavaScript 和基于组件的架构知识。

Both React and Vue share the same component-driven development approach, allowing developers to build applications in a modular way. Each component contains its functionalities and lifecycle. Vue takes these core concepts of modular coding and offers flexibility to developers in choosing which approach to use to write their components: JSX or the traditional style, in which HTML, CSS, and JavaScript are separated.

React 和 Vue 采用相同的组件驱动开发方法,允许开发人员以模块化方式构建应用程序。每个组件都包含其功能和生命周期。Vue 继承了这些模块化编码的核心理念,让开发人员可以灵活选择使用哪种方法编写组件: JSX 或传统风格(HTML、CSS 和 JavaScript 分离)。

Vue uses the Single-File Component (SFC) approach to leverage this modular structure into a single file while keeping the separation readable and understandable for developers.

Vue 使用单文件组件(SFC)方法将这种模块化结构整合到单个文件中,同时保持可读性和可理解性。

在项目中使用 Vue 的优势

Vue has a gentler learning curve and a vibrant ecosystem. This gentle learning curve helps reduce overhead and cost for any team onboarding developers to a new Vue project.

Vue 的学习曲线较为平缓,生态系统充满活力。这种平缓的学习曲线有助于减少任何团队为新的 Vue 项目培训开发人员的开销和成本。

One key benefit of Vue is its approachability for both new and veteran developers:

  • Out of the box, developers can use a well-optimized and performant framework on which to build scalable, dynamic frontend applications.
  • The SFC format pattern offers a modular and flexible blueprint that provides an enjoyable experience to developers. SFCs allow Vue to be genuinely versatile. You can implement basic functionalities and incrementally adopt pieces of a static site into Vue rather than overhaul your entire website.

Vue 的一个主要优点是它对于新老开发人员都很容易上手:

  • 开箱即用,开发人员可以使用优化良好、性能卓越的框架来构建可扩展的动态前端应用程序。
  • SFC 格式模式提供了一个模块化和灵活的蓝图,为开发人员带来了愉快的体验。SFC 使 Vue 成为真正的多面手。您可以实现基本功能,并逐步将静态网站的各个部分纳入 Vue,而不是彻底改造整个网站。

As powerful as Redux and NgRx, Vuex (and lately Pinia) proves to be an outstanding official global state management tool that is flexible enough to meet most development needs.

与 Redux 和 NgRx 一样强大的是,Vuex(以及最近的 Pinia)被证明是一款出色的官方全局状态管理工具,其灵活性足以满足大多数开发需求。

Thanks to its stable performance; well-defined tools such as Vue Router, Pinia, Vuex, and so on; and a supportive community, developers can save time and money by choosing Vue for their development stack.

得益于其稳定的性能、定义明确的工具(如 Vue Router、Pinia、Vuex 等)以及支持性社区,开发人员可以通过选择 Vue 作为其开发栈来节省时间和金钱。

The following section explores the essential Vue architecture before deepdiving into the SFC pattern and template syntax.

在深入探讨 SFC 模式和模板语法之前,下文将探讨 Vue 的基本架构。

使用 Vue

To learn about the Vue architecture, we will start by importing the Vue package into our coding playground. One straightforward way is to import the Vue package through the official Content Distribution Network (CDN).

要了解 Vue 架构,我们首先要将 Vue 软件包导入我们的编程环境。一种直接的方法是通过官方内容分发网络(CDN)导入 Vue 软件包。

We can do so by creating an index.html file and adding a <script> tag to load the Vue CDN within the <head> section of the HTML template, as demonstrated in the following code block:

我们可以创建一个 index.html 文件,并在 HTML 模板的 <head> 部分添加一个 <script> 标记来加载 Vue CDN,如下代码块所示:

<!DOCTYPE html>
<html>
<head>
    <title>Vue.js project with CDN</title>
    <script src="https://unpkg.com/vue@3"></script>
</head>
</html>

The browser will also load the Vue package using the CDN defined in the script tag when loading the page. Once completed, you can utilize the Vue functions and start writing Vue code.

在加载页面时,浏览器还会使用脚本标签中定义的 CDN 加载 Vue 包。完成后,您就可以使用 Vue 功能并开始编写 Vue 代码。

But first, let’s look at the Vue instance.

但首先,让我们来看看 Vue 实例。

了解Vue的实例

In general, each Vue application consists of only one root Vue instance, which can be created using the Vue.createApp method:

一般来说,每个 Vue 应用程序只包含一个根 Vue 实例,可以使用 Vue.createApp 方法创建:

const vm = Vue.createApp({
	// options
})

The Vue class constructor accepts an options object for the configurations and behavior of components. We call this approach Options API and we can use it for all corresponding Vue components. However, all of them are considered nested Vue instances, with their own options and properties.

Vue 类构造函数接受一个选项对象,用于组件的配置和行为。我们将这种方法称为选项 API,并将其用于所有相应的 Vue 组件。不过,所有这些组件都被视为嵌套的 Vue 实例,拥有各自的选项和属性。

NOTE:vm is a term commonly used to refer to a View Model, which is an abstraction of the view that describes the state of the data in the model. Binding a Vue instance to vm helps you to keep track of your Vue instance in a block of code.

注:vm 通常指视图模型(View Model),它是视图的一个抽象概念,用于描述模型中数据的状态。将 Vue 实例绑定到 vm 可帮助您在代码块中跟踪 Vue 实例。

For the Vue engine to render the application instance, in our index.html file, we declare an <div> element within the <body> tag using a unique class name, ID, or data attribute as the main entry point for the application accordingly:

为了让 Vue 引擎渲染应用程序实例,在 index.html 文件中,我们在 <body> 标记中声明了一个 <div> 元素,使用唯一的类名、ID 或数据属性作为应用程序的主要入口:

<body>
    <div id="vue-app"></div>
    <script>
        const vm = Vue.createApp({
        //Options
        })
    </script>
</body>

To render the Vue application in the browser, we need to trigger vm.mount() to mount the root component to the targeted HTML element using a unique selector. In this example, it is an id with a value of vue-app:

要在浏览器中呈现 Vue 应用程序,我们需要触发 vm.mount(),使用唯一选择器将根组件挂载到目标 HTML 元素上。在本例中,它是一个值为 vue-app 的 id:

<body>
    <div id="vue-app"></div>
    <script>
        const vm = Vue.createApp({
        	//Options
        })
        vm.mount('#vue-app')
    </script>
</body>

Now, you bind the <div> element with id=“vue-app” to the new Vue instance.

现在,将带有 id=“vue-app” 的 <div> 元素绑定到新的 Vue 实例。

Next, let’s define text with a value of “Start using Vue.js today!” and add it as a property of the return value for the data method in the application options:

接下来,让我们定义值为 "今天就开始使用 Vue.js!"的文本,并将其添加为应用程序选项中数据方法返回值的属性:

const vm = Vue.createApp({
    data() {
        return {
        	text: '今天就开始使用 Vue.js!'
        }
    }
})

In the preceding code example, data is a function that returns an Object instance containing the local state (or local variables) of a component.

在前面的代码示例中,data 是一个函数,它返回一个包含组件本地状态(或本地变量)的对象实例。

To render the content of text to the DOM, we use Vue template syntax, represented by double curly braces ({{}}) wrapped around the reactive content. In this case, we use {{ text }}, as shown in the following code:

要将文本内容呈现到 DOM 中,我们使用 Vue 模板语法,即用双大括号 ({{}}) 包住反应内容。在本例中,我们使用 {{ text }},如下代码所示:

<div id="vue-app">{{ text }}</div>

In the <head> tag, we can also use the DOM API to construct a Vue application instance and bound it to our target element (with the ID selector as #vue-app):

<head> 标记中,我们还可以使用 DOM API 构建一个 Vue 应用程序实例,并将其绑定到目标元素(ID 选择器为 #vue-app):

<head>
<title>Vue.js CDN</title>
<script src="https://unpkg.com/vue@3"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        Vue.createApp({
                data(){
                    return {
                        text: "Start using Vue.js today!"
                    }
            }
        }).mount('#vue-app')
    })
</script>
</head>
<body>
<div id="vue-app">{{text}}</div>
</body>

The output is the same for both approaches. However, we strongly recommend not using DOMContentLoaded.

两种方法的输出结果是一样的。不过,我们强烈建议不要使用 DOMContentLoaded。

最终完整代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vue3快速入门</title>
  </head>
  <body>
    <div id="vue-app">{{text}}</div>
    <script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            text: "今天就开始使用 Vue.js!",
          };
        },
      });
      app.mount("#vue-app");
    </script>
  </body>
</html>

文章来源:https://blog.csdn.net/qq_37703224/article/details/135037055
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。