Vue 3.0响应式API案例
什么是Proxy
proxy翻譯過來的意思就是”代理“,ES6對Proxy的定位就是target對象(原對象)的基礎(chǔ)上通過handler增加一層”攔截“,返回一個新的代理對象,之后所有在Proxy中被攔截的屬性,都可以定制化一些新的流程在上面,先看一個最簡單的例子。
其實(shí)ref除了可以獲取本頁面的dom元素,還可以拿到子組件中的data和去調(diào)用子組件中的方法
獲取子組件中的data
子組件
vue3 中 的 computed 的使用,由于 vue3 兼容 vue2 的選項(xiàng)式API,所以可以直接使用 vue2的寫法,這篇文章主要介紹 vue3 中 computed 的新用法,對比 vue2 中的寫法,讓您快速掌握 vue3 中 computed 的新用法。
組合式 API 中使用 computed 時(shí),需要先引入:import { computed } from “vue”。引入之后 computed 可以傳入的參數(shù)有兩種:回調(diào)函數(shù)和 options 。具體看看它是如何使用的?
一、函數(shù)式寫法
在vue2中,computed 寫法:
computed:{ sum(){ return this.num1+ this.num2 } }
在vue3 如果使用選項(xiàng)式API也可以這樣寫,主要看下組合式API的使用。
示例1:求和
import { ref, computed } from “vue” export default{ setup(){ const num1 = ref(1) const num2 = ref(1) let sum = computed(()=>{ return num1.value + num2.value }) } }
調(diào)用 computed 時(shí), 傳入了一個箭頭函數(shù),返回值作為 sum 。相比之前,使用更加簡單了。如果需要計(jì)算多個屬性值,直接調(diào)用就可以。如:
let sum = computed(()=>{ return num1.value + num2.value }) let mul = computed(()=>{ return num1.value * num2.value })
該示例過于簡單,看不明白的可在文章后面閱讀完整實(shí)例1。
二、options 寫法
計(jì)算屬性默認(rèn)只有 getter ,在需要的時(shí)候也可以提供 setter 。在vue2中用法如下:
computed:{ mul:{ get(){ // num1值改變時(shí)觸發(fā) return this.num1 * 10 }, set(value){ // mul值被改變時(shí)觸發(fā) this.num1 = value /10 } } }
mul 屬性是 給num1 放大10,如果修改 mul 的值,則 num1 也隨之改變。
在 vue3 中 :
let mul = computed({ get:()=>{ return num1.value *10 }, set:(value)=>{ return num1.value = value/10 } })
這兩種寫法不太一樣,仔細(xì)觀察區(qū)別不大,get 和 set 調(diào)用也是一樣的。
Vue3.0使用組件創(chuàng)建樹形項(xiàng)目分類綜合案例
<!DOCTYPE html> <html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>使用組件創(chuàng)建樹狀項(xiàng)目</title><script src="https://unpkg.com/vue@next"></script> </head><body><div id="app"><category-component :list="categories"></category-component></div><script>const CategoryComponent = {name: 'catComp',props: {list: { type: Array }},template: `<ul><template v-if="list"><li v-for="cat in list">{{cat.name}}<catComp :list="cat.children"/></li></template></ul>`}//繼續(xù)const app = Vue.createApp({data() {return {categories: [{name: 'JAVA編程講義',children: [{name: 'JAVA編程思想',children: [{ name: 'HTML開發(fā)技術(shù)' },{ name: 'JS開發(fā)技術(shù)' },{ name: 'Vue.js開發(fā)技術(shù)' }]}, {name: 'C#開發(fā)指南'}]},{name: 'JAVA編程講義',children: [{name: 'JAVA編程思想',children: [{ name: 'C#宿舍管理系統(tǒng)實(shí)戰(zhàn)' },{ name: 'Android開發(fā)技術(shù)' },{ name: '鴻蒙開發(fā)技術(shù)' }]}, {name: '張晨光老師帶你學(xué)Vue'}]}]}},components: {CategoryComponent}}).mount('#app');</script> </body></html> 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的Vue 3.0响应式API案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 周鸿祎称不理解35岁程序员被「抛弃」,网
- 下一篇: Vue3.js 全局组价案例入门