Table of Contents
Limitations of Vue2
What is ref" > What is ref
Summary" >Summary
三、Methods" >三、Methods
基础用法
自动拆装箱总结" >自动拆装箱总结
四、 Computed - 计算属性" >四、 Computed - 计算属性
五、Reactive - 响应式语法
Attending
六、 Modularizing
七、 LifecycleHooks - 生命周期钩子" >七、 LifecycleHooks - 生命周期钩子
八、Watch - 监听器
九、Sharing State - 共享状态
十、Suspense - 悬念
复杂的Loading实现
Suspense基础语法" >Suspense基础语法
骨架屏实现
十一、Teleport - 传送门" >十一、Teleport - 传送门
功能
基础语法" >基础语法
示例代码" >示例代码
Home Web Front-end Vue.js [Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

Aug 30, 2022 pm 08:20 PM
vue3

This article summarizes and shares Vue3 study notes, and provides an in-depth understanding of 11 knowledge points of Vue3. I hope it will be helpful to everyone!

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

Vue3 Node Webpack API Mall Project Engineering Practical Development Course!

1. Why choose CompositionAPI

Limitations of Vue2

  • Poor readability caused by component logic expansion
  • Unable to reuse code across components
  • Vue2 has limited support for TS

In the traditional OptionsAPI we need to spread the logic into the following six parts. [Related recommendations: vue.js video tutorial]

OptionsAPI

  • ##components
  • props
  • data
  • computed
  • methods
  • lifecycle methods
How to use CompositionAPI to solve the problem

The best solution is to aggregate the logic and the code can be very good Readability.

This is what our CompositionAPI syntax can achieve. CompositionAPI is a completely optional syntax and has no conflict with the original OptionAPI. It allows us to organize code with the same function together without scattering it to every corner of the optionsAPI

Code reuse method PK

Cross-component reuse code in Vue2, we There are probably four options

1. Mixin - Mixin

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

    Code mixing is actually the mixing mode in the design mode, and its shortcomings are also very obvious .
  • Can be understood as multiple inheritance. Simply put, it is how a person has two fathers
Disadvantages

    Cannot be avoided Attribute name conflict
  • Unclear inheritance relationship
2. Mixin Factory - Mixin Factory

returns a

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

✅Code reuse is convenient

✅Inheritance relationship cleaning

3. ScopeSlots - Scope slots

❌Not very readable

❌Configuration Complex - needs to be configured in the template

❌Low performance-each slot is equivalent to an instance

4, CompositionApi - composite API

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

✅Small amount of code

✅No new syntax is introduced, just a simple function

✅Exceptionally flexible

✅The tool syntax prompts are friendly-because it is a simple function, it is very Easy to implement syntax prompts and automatic compensation

2. setup & ref

Reason for using CompositionAPI

✅Better Typescript support

✅In complex functional components, code can be organized according to characteristics - code cohesion, such as:

Sort and search logic cohesion

✅Components Inter-code reuse

What is setup

    Execute before the following method:
    • Components
    • Props
    • Data
    • Methods
    • Computed Properties
    • Lifecycle methods
    ##can be no longer difficult to use Understand this
  • has two optional parameters
  • props - properties (responsive object and can be monitored (watch))
  • import {watch} from "vue"
    export defalut {
    	props: {
    		name: String
    	},
    	setup(props) {
    		watch(() => {
    			console.log(props.name)
    		})
    	}
    }
    Copy after login
context context object - used to replace the properties that can be accessed by the previous this method
  • setup (props,context) {
    	const {attrs,slots,parent,root,emit} = context
    }
    Copy after login
The boxing operation of basic data type data makes it a responsive object that can track data changes.

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3The maintainability is significantly improved

  • 可以控制哪些变量暴露
  • 可以跟中哪些属性被定义 (属性继承与引用透明)

基础用法

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

  • JS :需要通过.value访问包装对象
  • 模板: 自动拆箱

这个地方实在没什么好讲的,和Vue2没变化

<template>
  <div>
    <div>Capacity: {{ capacity }}</div>
    <p>Spases Left: {{ sapcesLeft }} out of {{ capacity }}</p>
    <button @click="increaseCapacity()">Increase Capacity</button>
  </div>
</template>

<script>

import { ref, computed, watch } from "vue";
export default {
  setup(props, context) {
    const capacity = ref(3);
    const attending = ref(["Tim", "Bob", "Joe"]);
    function increaseCapacity() {
      capacity.value++;
    }
    const sapcesLeft = computed(() => {
      return capacity.value - attending.value.length;
    });
    return { capacity, increaseCapacity, attending, sapcesLeft };
  },
};
</script>
Copy after login

五、Reactive - 响应式语法

之前reactive 的 Ref 去声明所有的响应式属性

import { ref,computed } from &#39;vue&#39;
export default {
  setup(){
    const capacity = ref(4);
    const attending = ref(["Tim","Bob","Joe"]);
    const spacesLeft = computed(()=>{
      return capacity.value - attending.value.length
    })
    function increaseCapacity(){ capacity.value ++;}
    return { capacity,increaseCapacity,attending,spacesLeft}
  }
}
Copy after login

但是有另一个等效的方法用它去代替 reactive 的Ref

import { reactive,computed } from &#39;vue&#39;
export default {
  setup(){
    const event = reactive({
      capacity:4,
      attending:["Tim","Bob","Joe"],
      spacesLeft:computed(()=>{
        return event.capacity - event.attending.length;
      })
    })
  }
}
Copy after login

过去我们用vue2.0的data来声明响应式对象,但是现在在这里每一个属性都是响应式的包括computed 计算属性

这2种方式相比于第一种没有使用.

接下来 我们再声明method 这2种语法都ok,取决于你选择哪一种

setup(){
  const event = reactive(){
    capacity:4,
    attending:["Tim","Bob","Joe"],
    spacesLeft:computed(()=>{
      return event.capacity - event.attending.length;
    })
    function increaseCapacity(){event.capacity++}
    //return整个对象
    return {event,increaseCapacity}
  }
}
Copy after login
<p>Spaces Left:{{event.spacesLeft}} out of {{event.capacity}}</p>
<h2 id="Attending">Attending</h2>
<ul>>
	<li v-for="(name,index) in event.attending" :key="index">
     {{name}}
  </li>
</ul>
<button @click="increaseCapacity()"> Increase Capacity</button>
Copy after login

在这里我们使用对象都是.属性的方式,但是如果 这个结构变化了,event分开了编程了一个个片段,这个时候就不能用.属性的方式了

//在这里可以使用toRefs
import {reactive,computed,toRefs} from &#39;vue&#39;
export default{
  setup(){
    const event = reactive({
      capacity:4,
      attending:["Tim","Bob","Joe"],
      spacesLeft:computed(()=>{
        return event.capacity -event.attending.length;
        
      })
    })
    function increaseCapacity(){ event.capacity ++ }
    return {...toRefs(event),increaseCapacity}
  }
}
Copy after login

如果没有 increaseCapacity() 这个方法 直接可以简化为

return toRefs(event)
Copy after login

完整代码

<div>
   <p>Space Left : {{event.spacesLeft}} out of {{event.capacity}} </p>
   <h2 id="Attending">Attending</h2>
   <ul>
      <li v-for="(name,index)" in event.attending :key="index">{{name}}
      </li>


     
   </ul>
   <button @click="increaseCapacity">Increase Capacity</button>
   </div>
</template>

<script>
//第一种
import {ref,computed } from &#39;vue&#39;
export default {
  setup(){
    const capacity = ref(4)
    const attending = ref(["Tim","Bob","Joe"])
    const spaceLeft = computed(()=>{
      return capacity.value - attending.value.length;
    });
    function increaseCapacity(){ capacity.value++; }
    return {capacity,increaseCapacity,attending,spaceLeft}   


  }
} 

//返回一个响应式函数 第二种
import { reactive,computed } from &#39;vue&#39;
export default {
  setup(){
    const event = reactive({
      capacity:4,
      attending:["Tim","Bob","Joe"],
      spaceLeft:computed(()=>{
        return event.capacity - event.attending.length;
      })
    })
    //我们不再使用.value
    function increaseCapacity() { event.capacity++; }
    //把这个event放入到template中
    return { event,increaseCapacity}
  }
}


</script>
Copy after login

六、 Modularizing

使用CompositionAPI的两个理由

1、可以按照功能组织代码

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

2、组件间功能代码复用

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

Vue2Vue3
beforeCreate❌setup(替代)
created❌setup(替代)
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeDestroyonBeforeUnmount
destroyedonUnmounted
errorCapturedonErrorCaptured
-?onRenderTracked
-?onRenderTriggered

setup中调用生命周期钩子

import { onBeforeMount,onMounted } from "vue";
export default {
  setup() {
    onBeforeMount(() => {
        console.log(&#39;Before Mount!&#39;)
    }) 
    onMounted(() => {
        console.log(&#39;Before Mount!&#39;)
    }) 
  },
};
Copy after login

八、Watch - 监听器

// 所有依赖响应式对象监听
watchEffect(() => {
   results.value = getEventCount(searchInput.value);
 });

// 特定响应式对象监听
watch(
  searchInput,
  () => {
    console.log("watch searchInput:");
  }
);

// 特定响应式对象监听 可以获取新旧值
watch(
  searchInput,
 (newVal, oldVal) => {
    console.log("watch searchInput:", newVal, oldVal);
  },
);

// 多响应式对象监听
watch(
  [firstName,lastName],
 ([newFirst,newLast], [oldFirst,oldlast]) => {
   // .....
  },
  
);

// 非懒加载方式监听 可以设置初始值
watch(
  searchInput,
  (newVal, oldVal) => {
    console.log("watch searchInput:", newVal, oldVal);
  },
  {
    immediate: true, 
  }
);
Copy after login

九、Sharing State - 共享状态

[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

编写一个公共函数usePromise函数需求如下:

  • results : 返回Promise执行结果
  • loading: 返回Promise运行状态
    • PENDING :true
    • REJECTED : false
    • RESOLVED: false
  • error : 返回执行错误

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

import { ref } from "vue";

export default function usePromise(fn) {
  const results = ref(null);
  // is PENDING
  const loading = ref(false);
  const error = ref(null);

  const createPromise = async (...args) => {
    loading.value = true;
    error.value = null;
    results.value = null;
    try {
      results.value = await fn(...args);
    } catch (err) {
      error.value = err;
    } finally {
      loading.value = false;
    }
  };
  return { results, loading, error, createPromise };
}
Copy after login

应用

import { ref, watch } from "vue";
import usePromise from "./usePromise";
export default {
  setup() {
    const searchInput = ref("");
    function getEventCount() {
      return new Promise((resolve) => {
        setTimeout(() => resolve(3), 1000);
      });
    }

    const getEvents = usePromise((searchInput) => getEventCount());

    watch(searchInput, () => {
      if (searchInput.value !== "") {
        getEvents.createPromise(searchInput);
      } else {
        getEvents.results.value = null;
      }
    });

    return { searchInput, ...getEvents };
  },
};
Copy after login

十、Suspense - 悬念

复杂的Loading实现

我们考虑一下当你加载一个远程数据时,如何显示loading状态

通常我们可以在模板中使用v-if

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

但是在一个组件树中,其中几个子组件需要远程加载数据,当加载完成前父组件希望处于Loading状态时我们就必须借助全局状态管理来管理这个Loading状态

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

这个问题在Vue3中有一个全新的解决方法。

这就是Suspense Component,悬念组件。

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

<template>
  <div>
    <div v-if="error">Uh oh .. {{ error }}</div>
    <Suspense>
      <template #default>
        <div>
          <Event />
          <AsyncEvent />
        </div>
      </template>
      <template #fallback> Loading.... </template>
    </Suspense>
  </div>
</template>

<script>
import { ref, onErrorCaptured, defineAsyncComponent } from "vue";

import Event from "./Event.vue";

const AsyncEvent = defineAsyncComponent(() => import("./Event.vue"));
export default {
  components: {
    Event,
    AsyncEvent,
  },

  setup() {
    const error = ref(null);
    onErrorCaptured((e) => {
      error.value = e;
      // 阻止错误继续冒泡
      return true;
    });
    return { error };
  },
};
</script>
Copy after login

骨架屏实现

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

功能

类似React中的Portal, 可以将特定的html模板传送到Dom的任何位置

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

通过选择器QuerySelector配置

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

1[Compilation and summary] Detailed explanation of 11 knowledge points of Vue3

<template>
  <div>
    <teleport to="#end-of-body" :disabled="!showText">
      <!-- 【Teleport : This should be at the end 】 -->
      <div>
        <video  muted controls="controls" autoplay="autoplay" loop="loop">
          
        </video>
      </div>
    </teleport>
    <div>【Teleport : This should be at the top】</div>
    <button @click="showText = !showText">Toggle showText</button>
  </div>
</template>
<script>
import { ref } from "vue";
export default {
  setup() {
    const showText = ref(false);
    setInterval(() => {
      showText.value = !showText.value;
    }, 1000);
    return { showText };
  },
};
</script>
Copy after login

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of [Compilation and summary] Detailed explanation of 11 knowledge points of Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

How to use tinymce in vue3 project How to use tinymce in vue3 project May 19, 2023 pm 08:40 PM

tinymce is a fully functional rich text editor plug-in, but introducing tinymce into vue is not as smooth as other Vue rich text plug-ins. tinymce itself is not suitable for Vue, and @tinymce/tinymce-vue needs to be introduced, and It is a foreign rich text plug-in and has not passed the Chinese version. You need to download the translation package from its official website (you may need to bypass the firewall). 1. Install related dependencies npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2. Download the Chinese package 3. Introduce the skin and Chinese package. Create a new tinymce folder in the project public folder and download the

How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

How Vue3 parses markdown and implements code highlighting How Vue3 parses markdown and implements code highlighting May 20, 2023 pm 04:16 PM

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

How to solve the problem that after the vue3 project is packaged and published to the server, the access page displays blank How to solve the problem that after the vue3 project is packaged and published to the server, the access page displays blank May 17, 2023 am 08:19 AM

After the vue3 project is packaged and published to the server, the access page displays blank 1. The publicPath in the vue.config.js file is processed as follows: const{defineConfig}=require('@vue/cli-service') module.exports=defineConfig({publicPath :process.env.NODE_ENV==='production'?'./':'/&

How to select an avatar and crop it in Vue3 How to select an avatar and crop it in Vue3 May 29, 2023 am 10:22 AM

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

How to use Vue3 reusable components How to use Vue3 reusable components May 20, 2023 pm 07:25 PM

Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

See all articles