Vue.js

Vue官方文档:https://cn.vuejs.org/guide/introduction.html

Vue使用方式

独立脚本方式

Vue可以像jQuery一样作为一个独立的JavaScript库直接引入到HTML中,适用于快速原型开发或小型项目。

实现步骤

  • 下载Vue.js文件或从CDN引用。
  • 在HTML中引入Vue.js文件。
  • 直接在页面上使用Vue实例。
html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue独立脚本示例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
    <div id="app">
        {{ message }}
    </div>
    <script>
        new Vue({
            el: '#app',
            data: {
                message: 'Hello Vue with script tag!'
            }
        });
    </script>
</body>
</html>

WebComponent

参照vue文档: Vue 与 Web Components

Vue可以通过Custom Elements规范(Web Components的一部分)封装成自定义元素,使其能够在任何支持Web Components的环境中使用。

实现步骤

  • 使用Vue的Vue.defineComponentVue.createApp来定义和创建组件。
  • 通过defineCustomElement将其转换为自定义元素。
  • 注册自定义元素。

代码示例(Vue 3):

javascript
// MyComponent.js
import { defineComponent, defineCustomElement } from 'vue';

const MyComponent = defineComponent({
  template: '<h1>Hello from Web Component!</h1>'
});

customElements.define('my-vue-component', defineCustomElement(MyComponent));

在HTML中使用自定义元素:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue as Web Component</title>
    <script src="https://unpkg.com/vue@next"></script>
    <script src="MyComponent.js"></script> <!-- 引入上面编写的Vue组件 -->
</head>
<body>
    <my-vue-component></my-vue-component>
</body>
</html>

使用脚手架工具

create-vue@vue/cli都是Vue.js项目创建工具

  • @vue/cli是Vue.js官方提供的现代化的命令行工具(Vue CLI),用于快速搭建Vue项目的脚手架。它支持Vue 2和Vue 3的项目创建,并且集成了项目模板选择、配置管理、插件安装等功能。
bash
npm install -g @vue/cli
# npm update -g @vue/cli

vue create hello-world
# vue ui   # 以图形化界面创建和管理项目

cd hello-world
npm run serve
bash
npx @vue/cli create my-vue-app

cd my-vue-app
npm run serve

早期Vue CLI的包名为vue-cli(主要对应Vue CLI 2.x版本),后来改名为@vue/cli(Vue CLI 3.x及以上版本),引入了许多改进,包括更好的配置灵活性、Vue UI图形界面、更快的项目初始化速度等

  • create-vue 是针对Vue3的简化创建工具,专为Vue 3项目设计,使用Vite作为默认的构建工具,而非Webpack。
bash
npm create vue@latest
# npm create vue@legacy   # Vue 2 (support IE11)

cd vue-project
npm install
npm run format
npm run dev

全栈/SSR

Vue支持 服务器端渲染(Server-Side Rendering),这可以改善SEO和首屏加载速度。

实现步骤

  • 使用@vue/cli-plugin-ssrnuxt.js等工具。
  • 配置服务器端渲染相关设置。
  • 在服务器上渲染Vue应用并返回HTML字符串。

使用Nuxt.js的示例

  • 首先安装Nuxt.js:
bash
npm install -g create-nuxt-app
create-nuxt-app my-ssr-app
  • 选择需要的选项,如服务器渲染支持。
  • 开发和配置应用,Nuxt.js会自动处理SSR相关的配置和路由。
  • 运行应用:
bash
cd my-ssr-app
npm run dev

Vue3常见特性

组合式API

  • Vue 2 主要使用选项式API(Options API),逻辑分散在 data, methods, computed, watch 等属性中。
  • Vue 3 强烈推荐使用组合式API(Composition API),它允许你通过 setup() 函数集中管理组件的状态和逻辑,更易于复用和组织代码。
javascript
// 选项式API(Options API)逻辑分散在 `data`, `methods`, `computed`, `watch` 等属性中
export default {
  data() {
    return {
      count: 0
    };
  },
  methods: {
    increment() {
      this.count++;
    }
  },
  computed: {
    doubleCount() {
      return this.count * 2;
    }
  },
  watch: {
    count(newValue, oldValue) {
      console.log(`count changed from ${oldValue} to ${newValue}`);
    }
  }
};
javascript
import { ref, computed, watch } from 'vue';
// 在组合式API中,我们使用 `ref` 来定义响应式变量,`computed` 来创建计算属性,`watch` 来观察变化
// 并通过 `setup()` 函数集中管理这些逻辑,使代码更易于理解和维护

export default {
  setup() {
    const count = ref(0);

    function increment() {
      count.value++;
    }

    const doubleCount = computed(() => count.value * 2);

    watch(count, (newValue, oldValue) => {
      console.log(`count changed from ${oldValue} to ${newValue}`);
    });

    return {
      count,
      increment,
      doubleCount
    };
  }
};

生命周期钩子

  • Vue 2 使用传统的生命周期钩子函数,如 created, mounted, updated, destroyed 等。
  • Vue 3 引入了新的生命周期钩子,如 setup(),它在组件创建之初被调用,且不能访问 this。同时,一些原有的生命周期钩子在Vue 3中被重命名或废弃,比如 beforeDestroy 变为 beforeUnmount

多根节点支持

  • Vue 2 要求每个组件模板有一个根元素,否则会报错。
  • Vue 3 支持多根节点,可以返回多个顶级元素,它们会被自动包裹在一个虚拟的Fragment中。

TypeScript支持

  • Vue 2 虽然可以与TypeScript一起使用,但选项式API对TypeScript的支持不如Vue 3自然。
  • Vue 3 有更好的TypeScript集成,特别是在使用组合式API时,类型推导更加准确和方便。

响应式系统

  • Vue 2 使用 Object.defineProperty 实现响应式。
  • Vue 3 使用 Proxy,提供了更强大的响应式系统,可以监听数组、对象的所有属性变化,包括新增和删除。

Vite构建工具

  • Vue 2 传统上使用webpack进行构建。
  • Vue 3 推荐使用Vite,它基于ES模块热更新,启动和更新速度更快。

Vite 是一个轻量级的、速度极快的构建工具,对 Vue SFC 提供第一优先级支持