Vue3.0 全面探索 基于 Visual Studio Code 的代码片段开发插件

摘要:
PrefixJavaScriptSnippetContentimportimport{…}from“@vue/composition api”importimport}from'vu'newVuenewVuecreateComponentcreateComponentexportexportdefault{…}setupsetup{..}reactiveconstdata=reactivewatchwatchFnwatchcomputedtoRefstoRefs(…)refref(…)propsprops(……)on BeforeMountonBeforeMount(…)on Mounted(…)onBeforeUpdateonBeforeUpdate(…)。。。)在卸载之前卸载之前(…)在卸载之后卸载(…)错误捕获错误捕获(…)VueCompositionAPIVueCompositionAPI@vue/组合api使开发人员能够使用Vue 2.x中Vue 3.0中引入的基于函数的逻辑重用机制。English Version NavigationInstallation/Installation Usage/use TypeScriptTSXLsimulations/Restrict APIChangelog/Change LogInstallationnpmnpminstall@vue / composition-api--saveyarnyarnadd@vue/composition apiCDN通过使用全局变量window.vueCompositionApi。它通过全局变量window.vueCompositionApi使用。UsageYoumustinstall@vue/成分apiviaVue。在使用@vue/compositionapi提供的任何功能之前,必须首先通过vue进行安装。use():从'vue'导入vue;importVueCompositionApifrom'@vue/compositionapi';Vue公司。使用安装插件后,您可以使用组件API组合组件。安装插件后,您可以使用新的Composition API来开发组件。TypeScriptThisplugin要求TypeScriptversion˃3.5.1。如果您正在使用vetur,请确保已安装。请使用WorkspaceDependencies来实现。允许TypeScript在VueComponent选项中正确推断类型,您需要使用createComponent定义组件:请使用最新版本的TypeScript。如果你用蔬菜,请放蔬菜。useWorkspaceDependencies设置为true。
Vue3 Snippets for Visual Studio Code

This extension adds Vue3 Code Snippets into Visual Studio Code.

这个插件基于最新的 Vue3 的 API 添加了 Code Snippets。

Vue3.0 全面探索 基于 Visual Studio Code 的代码片段开发插件第1张Snippets / 代码片段

Including most of the API of Vue3. You can type reactive, choose reactive, and press ENTER, then const data = reactive({...}) appear on the screen.

插件的 Snippets 如下表格所示,比如你可以键入 reactive 然后按上下键选中 reactive 再按 Enter 键,就输入了const data = reactive({...})了。

PrefixJavaScript Snippet Content
importimport {...} from "@vue/composition-api"
importimport {...} from 'vue'
newVuenewVue({...})
createComponentcreateComponent({...})
exportexport default { ... }
setupsetup(${...}) {...}
reactiveconst data = reactive({...})
watchwatch(..., ...)
watchFnwatch(() => {...})
computedcomputed(() => { get: () => {...}, set: () => {...}})
toRefstoRefs(...)
refref(...)
propsprops(...)
onBeforeMountonBeforeMount(...)
onMountedonMounted(...)
onBeforeUpdateonBeforeUpdate(...)
onUpdatedonUpdated(...)
onBeforeUnmountonBeforeUnmount(...)
onUnmountedonUnmounted(...)
onErrorCapturedonErrorCaptured(...)
Vue Composition API

Vue Composition API

@vue/composition-api 使开发者们可以在 Vue 2.x 中使用 Vue 3.0 引入的基于函数逻辑复用机制

English Version


Navigation Installation

npm

npm install @vue/composition-api --save

yarn

yarn add @vue/composition-api

CDN

<script src="https://unpkg.com/@vue/composition-api/dist/vue-composition-api.umd.js"></script>

By using the global variable window.vueCompositionApi.

通过全局变量 window.vueCompositionApi 来使用。

Usage

You must install @vue/composition-api via Vue.use() before using other APIs:

在使用任何 @vue/composition-api 提供的能力前,必须先通过 Vue.use() 进行安装:

import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);

After installing the plugin you can use the Composition API to compose your component.

安装插件后,您就可以使用新的 Composition API 来开发组件了。

TypeScript

This plugin requires TypeScript version >3.5.1. If you are using vetur, make sure to set vetur.useWorkspaceDependencies to true.

To let TypeScript properly infer types inside Vue component options, you need to define components with createComponent:

请使用最新版的 TypeScript,如果你使用了 vetur,请将 vetur.useWorkspaceDependencies 设为 true

为了让 TypeScript 正确的推导类型,我们必须使用 createComponent 来定义组件:

import { createComponent } from '@vue/composition-api';

const Component = createComponent({
  // 启用类型推断
});

const Component = {
  // 无法进行选项的类型推断
  // TypeScript 无法知道这是一个 Vue 组件的选项对象
};

TSX

An Example Repository with TS and TSX support is provided to help you start.

To support TSX, create a declaration file with following content in your project.

这里有一个配置好 TS/TSX 支持的示例仓库来帮助你快速开始.

要支持 TSX,请创建一个类型定义文件并提供正确的 JSX 定义。内容如下:

// file: shim-tsx.d.ts`
import Vue, { VNode } from 'vue';
import { ComponentRenderProxy } from '@vue/composition-api';

declare global {
  namespace JSX {
    // tslint:disable no-empty-interface
    interface Element extends VNode {}
    // tslint:disable no-empty-interface
    interface ElementClass extends ComponentRenderProxy {}
    interface ElementAttributesProperty {
      $props: any; // specify the property name to use
    }
    interface IntrinsicElements {
      [elem: string]: any;
    }
  }
}
Limitations

Ref Unwrap

Unwrap is not working with Array index.

数组索引属性无法进行自动的Unwrap:

Should not store ref as a direct child of Array:

不要使用 Array 直接存取 ref 对象:

const state = reactive({
  list: [ref(0)],
});
// no unwrap, `.value` is required
state.list[0].value === 0; // true

state.list.push(ref(1));
//  no unwrap, `.value` is required
state.list[1].value === 1; // true

Should not use ref in a plain object when working with Array:

不要在数组中使用含有 ref 的普通对象:

const a = {
  count: ref(0),
};
const b = reactive({
  list: [a], // a.count will not unwrap!!
});

// no unwrap for `count`, `.value` is required
b.list[0].count.value === 0; // true
const b = reactive({
  list: [
    {
      count: ref(0), // no unwrap!!
    },
  ],
});

// no unwrap for `count`, `.value` is required
b.list[0].count.value === 0; // true

Should always use ref in a reactive when working with Array:

应该总是将 ref 存放到 reactive 对象中:

const a = reactive({
  count: ref(0),
});
const b = reactive({
  list: [a],
});
// unwrapped
b.list[0].count === 0; // true

b.list.push(
  reactive({
    count: ref(1),
  })
);
// unwrapped
b.list[1].count === 1; // true

Using reactive will mutate the origin object

reactive 会返回一个修改过的原始的对象

This is an limitation of using Vue.observable in Vue 2.

此行为与 Vue 2 中的 Vue.observable 一致

Vue 3 will return an new proxy object.

Vue 3 中会返回一个新的的代理对象.


watch() API

onTrack and onTrigger are not available in WatchOptions.

不支持 onTrackonTrigger 选项。


Template Refs

✅ Support ❌ Not Supported

✅ String ref && return it from setup():

<template>
  <div ref="root"></div>
</template>

<script>
  export default {
    setup() {
      const root = ref(null);

      onMounted(() => {
        // the DOM element will be assigned to the ref after initial render
        console.log(root.value); // <div/>
      });

      return {
        root,
      };
    },
  };
</script>

✅ String ref && return it from setup() && Render Function / JSX:

export default {
  setup() {
    const root = ref(null);

    onMounted(() => {
      // the DOM element will be assigned to the ref after initial render
      console.log(root.value); // <div/>
    });

    return {
      root,
    };
  },
  render() {
    // with JSX
    return () => <div ref="root" />;
  },
};

❌ Function ref:

<template>
  <div :ref="el => root = el"></div>
</template>

<script>
  export default {
    setup() {
      const root = ref(null);

      return {
        root,
      };
    },
  };
</script>

❌ Render Function / JSX in setup():

export default {
  setup() {
    const root = ref(null);

    return () =>
      h('div', {
        ref: root,
      });

    // with JSX
    return () => <div ref={root} />;
  },
};

If you really want to use template refs in this case, you can access vm.$refs via SetupContext.refs.

如果你依然选择在 setup() 中写 render 函数,那么你可以使用 SetupContext.refs 来访问模板引用,它等价于 Vue 2.x 中的 this.$refs:

⚠️ Warning: The SetupContext.refs won't exist in Vue 3.0. @vue/composition-api provide it as a workaround here.

⚠️ 警告: SetupContext.refs 并不属于 Vue 3.0 的一部分, @vue/composition-api 将其曝光在 SetupContext 中只是临时提供一种变通方案。

export default {
  setup(initProps, setupContext) {
    const refs = setupContext.refs;
    onMounted(() => {
      // the DOM element will be assigned to the ref after initial render
      console.log(refs.root); // <div/>
    });

    return () =>
      h('div', {
        ref: 'root',
      });

    // with JSX
    return () => <div ref="root" />;
  },
};

You may also need to augment the SetupContext when working with TypeScript:

如果项目使用了 TypeScript,你还需要扩展 SetupContext 类型:

import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);

declare module '@vue/composition-api/dist/component/component' {
  interface SetupContext {
    readonly refs: { [key: string]: Vue | Element | Vue[] | Element[] };
  }
}
SSR

Even if there is no definitive Vue 3 API for SSR yet, this plugin implements the onServerPrefetch lifecycle hook that allows you to use the serverPrefetch hook found in the classic API.

import { onServerPrefetch } from '@vue/composition-api';

export default {
  setup (props, { ssrContext }) {
    const result = ref();

    onServerPrefetch(async () => {
      result.value = await callApi(ssrContext.someId);
    });

    return {
      result,
    };
  },
};
项目源码

如果文章和笔记能带您一丝帮助或者启发,请不要吝啬你的赞和 Star,你的肯定是我前进的最大动力

免责声明:文章转载自《Vue3.0 全面探索 基于 Visual Studio Code 的代码片段开发插件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇XFS 文件系统的备份与还原WPF的依赖属性下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

hwclock和date源码分析

一. hwclock 1.1 hwclock源码在哪里? util-linux 或者busybox 1.2 获取源码 git clone https://github.com/karelzak/util-linux.git 或 git clonegit://git.busybox.net/busybox 1.3 hwclock的源码路径 sys-utils...

快速创建 Vue 项目

转载:https://www.jianshu.com/p/c7df292915e7 为了便于 Vue 项目的管理, Vue 团队官方开发了 vue-cli 工具。 本文将带您使用 vue-cli 快速创建一个 Vue 项目。 本地安装 vue-cli 使用 npm 全局安装 vue-cli : cnpm install -g @vue/cli 创建项目 执...

vue的axios使用

1.安装axios在项目目录下安装,命令: npm install --save axios vue-axios 2.axios的配置方法1:在入口main.js中导入axios 并将axios写入vue的原型,这样就能更简单的使用 import axios from 'axios'import VueAxios from 'vue-axios'​Vue....

QNAP container station安装 docker-mysql

打开container station,即docker,安装MySQL 选择最新的即可 点击创建后,就慢慢等待下载完成即可~ ,下载完成后会自动启动 尝试登陆mysql 密码在启动日志里,所以我们接下去找一下 执行如下命令mysql -u root -p密码复制过来,进入MySQL 到此就安装成功了,之后可进行修改密码和允许远程访问操作...

vue 服务端渲染 vs 预渲染(1)

服务端渲染: 1、将完整的html输出到客户端 2、要使用通用代码 优点 :  1、首次渲染快(无需等所有的js都完成下载)   2、利于seo 缺点:  1、更多的服务器负载 2、开发受限 3、需要处于node.js/php server 运行环境 预渲染:  1、使用少数营销页的seo   2、生成对特定路由静态的html文件 优点:   1、预渲染更...

[Vuejs] svg-sprite-loader实现加载svg自定义组件

1、安装 svg-sprite-loader npm install svg-sprite-loader -D 或者 npm install svg-sprite-loader --save-dev 2、将所有svg图片放到assets/svg下,以此为例,修改文件 build/webpack.base.conf.js 找到代码: { test: /....