首頁  >  文章  >  web前端  >  【整理總結】詳解Vue3的11個知識點

【整理總結】詳解Vue3的11個知識點

青灯夜游
青灯夜游轉載
2022-08-30 20:20:512972瀏覽

這篇文章總結分享Vue3學習筆記,深入了解Vue3的11個知識點,希望對大家有幫助!

【整理總結】詳解Vue3的11個知識點

Vue3 Node Webpack API 商城專案工程化實戰開發課程!

一、為什麼選擇CompositionAPI

Vue2的限制

  • 元件邏輯膨脹導致的可讀性變異
  • 無法跨元件重複使用程式碼
  • Vue2對TS的支援有限
##在傳統的OptionsAPI中我們需要將邏輯分散到以下六個部分。 【相關推薦:

vue.js影片教學

OptionsAPI

  • components

【整理總結】詳解Vue3的11個知識點

"

#props

  • data
#computed

methods

【整理總結】詳解Vue3的11個知識點

lifecycle methods

如何使用CompositionAPI解決問題

最佳的解決方法是將邏輯聚合就可以很好的程式碼可讀性。

這就是我們的CompositionAPI語法能夠實現的功能。 CompositionAPI是一個完全可選的語法與原來的OptionAPI並沒有衝突之處。他可以讓我們將相同功能的程式碼組織在一起,而不需要散落到optionsAPI的各個角落

#程式碼重用方法PK

Vue2中的跨元件重用程式碼,我們大概會有四個選擇【整理總結】詳解Vue3的11個知識點

1、Mixin - 混入

#程式碼混入其實就是設計模式中的混合模式,缺點也非常明顯。

可以理解為多重繼承,簡單的說就是一個人如何有兩個父親

#缺點

##都無法避免屬性名稱衝突繼承關係不清晰

2、Mixin Factory - 混入工廠


返回一個

    • #✅程式碼重複使用方便
  • ✅繼承關係清洗
  • 3、ScopeSlots - 作用域插槽
    • ❌可讀性不高
    • #❌配置複雜- 需要再模板中進行配置
  • ❌性能低- 每個插槽相當於一個實例
4、CompositionApi - 複合API
✅程式碼量少
✅沒有引入新的語法,只是單純函數

✅異常靈活✅工具語法提示友好- 因為是單純函數所以很容易實作語法提示、自動補償

二、setup & ref

使用CompositionAPI理由

✅更好的Typescript支援

【整理總結】詳解Vue3的11個知識點✅在複雜功能元件中可以實現根據特性組織程式碼- 程式碼內聚性, 例如:

排序與搜尋邏輯內聚

✅元件間程式碼復用###############setup是什麼#############在下列方法前執行:######Components### ###Props######Data######Methods######Computed Properties######Lifecycle methods############可以不在使用難於理解的this######有兩個可選參數######props - 屬性(響應式物件且可以監聽(watch))###############
import {watch} from "vue"
export defalut {
	props: {
		name: String
	},
	setup(props) {
		watch(() => {
			console.log(props.name)
		})
	}
}
#########context 上下文物件- 用於取代先前的this方法可以存取的屬性########
setup (props,context) {
	const {attrs,slots,parent,root,emit} = context
}
################################################################### ref是什麼############對基本資料類型資料進行裝箱操作使得成為一個響應式對象,可以追蹤資料變化。 ##################總結###################可維護性明顯提高###
  • 可以控制哪些变量暴露
  • 可以跟中哪些属性被定义 (属性继承与引用透明)

三、Methods

基础用法

【整理總結】詳解Vue3的11個知識點

自动拆装箱总结

【整理總結】詳解Vue3的11個知識點

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

四、 Computed - 计算属性

这个地方实在没什么好讲的,和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>

五、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}
  }
}

但是有另一个等效的方法用它去代替 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;
      })
    })
  }
}

过去我们用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}
  }
}
<p>Spaces Left:{{event.spacesLeft}} out of {{event.capacity}}</p>
<h2>Attending</h2>
<ul>>
	<li v-for="(name,index) in event.attending" :key="index">
     {{name}}
  </li>
</ul>
<button @click="increaseCapacity()"> Increase Capacity</button>

在这里我们使用对象都是.属性的方式,但是如果 这个结构变化了,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}
  }
}

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

return toRefs(event)

完整代码

<div>
   <p>Space Left : {{event.spacesLeft}} out of {{event.capacity}} </p>
   <h2>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>

六、 Modularizing

使用CompositionAPI的两个理由

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

【整理總結】詳解Vue3的11個知識點

2、组件间功能代码复用

【整理總結】詳解Vue3的11個知識點

【整理總結】詳解Vue3的11個知識點

七、 LifecycleHooks - 生命周期钩子

Vue2 Vue3
beforeCreate ❌setup(替代)
created ❌setup(替代)
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured
- ?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;)
    }) 
  },
};

八、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, 
  }
);

九、Sharing State - 共享状态

【整理總結】詳解Vue3的11個知識點

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

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

1【整理總結】詳解Vue3的11個知識點

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

应用

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 };
  },
};

十、Suspense - 悬念

复杂的Loading实现

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

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

1【整理總結】詳解Vue3的11個知識點

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

1【整理總結】詳解Vue3的11個知識點

Suspense基础语法

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

这就是Suspense Component,悬念组件。

1【整理總結】詳解Vue3的11個知識點

<template>
  <div>
    <div>Uh oh .. {{ error }}</div>
    <suspense>
      <template>
        <div>
          <event></event>
          <asyncevent></asyncevent>
        </div>
      </template>
      <template> 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>

骨架屏实现

1【整理總結】詳解Vue3的11個知識點

1【整理總結】詳解Vue3的11個知識點

十一、Teleport - 传送门

功能

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

1【整理總結】詳解Vue3的11個知識點

基础语法

通过选择器QuerySelector配置

1【整理總結】詳解Vue3的11個知識點

示例代码

1【整理總結】詳解Vue3的11個知識點

<template>
  <div>
    <teleport>
      <!-- 【Teleport : This should be at the end 】 -->
      <div>
        <video>
          
        </video>
      </div>
    </teleport>
    <div>【Teleport : This should be at the top】</div>
    <button>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>

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

以上是【整理總結】詳解Vue3的11個知識點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:poetries。如有侵權,請聯絡admin@php.cn刪除