vue3中使用ref語法糖的示例代碼
自從引入組合式 API 的概念以來,一個主要的未解決的問題就是 ref 和響應(yīng)式對象到底用哪個。響應(yīng)式對象存在解構(gòu)丟失響應(yīng)性的問題,而 ref 需要到處使用 .value 則感覺很繁瑣,并且在沒有類型系統(tǒng)的幫助時很容易漏掉 .value
以上是官方原話,大概就是新的語法糖,可以讓我們更方便的使用ref,而不用每次都寫.value,大概就是把這樣的代碼,簡化成這樣
import { ref } from 'vue'
const count = ref(0)
console.log(count.value)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">{{ count }}</button>
</template>簡化成這樣
<script setup lang="ts">
let count = $ref(0)
console.log(count)
function increment() {
count++
}
</script>
<template>
<button @click="increment">{{ count }}</button>
</template>每一個會返回 ref 的響應(yīng)式 API 都有一個相對應(yīng)的、以 $ 為前綴的宏函數(shù)。包括以下這些 API:
- ref -> $ref
- computed -> $computed
- shallowRef -> $shallowRef
- customRef -> $customRef
- toRef -> $toRef
多余的不再贅述,大家可以自行查看官方文檔,接下來我們來看看這個語法糖的具體使用,在項目中怎么配置
第一步(必須),在vite中啟用語法糖開關(guān)
打開vite.config.ts,添加如下代碼
vue({
reactivityTransform: true, // 啟用響應(yīng)式語法糖$ref $computed $toRef
})第二步(可選),配置tsconfig.json
在compilerOptions下添加vue/ref-macros, 不然會報錯TS2304: Cannot find name '$ref'.雖然不影響使用,但是會影響開發(fā)體驗
"compilerOptions":{
...
"types": ["vue/ref-macros"]
}第三步(可選),配置eslint
在eslintrc.cjs中加上global,不然會提示ESLint: '$ref' is not defined.(no-undef)
module.exports = {
...
globals: {
$ref: "readonly",
$computed: "readonly",
$shallowRef: "readonly",
$customRef: "readonly",
$toRef: "readonly",
}
};如果不嫌麻煩,又不想代碼中總是有誤報錯誤的行為,可以直接在vue代碼中引入vue/ref-macros,這樣就不用配置tsconfig.json和eslint了,也就是剛剛寫的第二,第三步
<script setup lang="ts">
import { $ref } from "vue/macros";
let count = $ref(0)
console.log(count)
function increment() {
count++
}
</script>
<template>
<button @click="increment">{{ count }}</button>
</template>vue3的ref用法
使用ref函數(shù)定義一個變量,ref擴(kuò)號里是變量的初始值
import?{ ref?}?from?'vue'
let conter=ref(0)
let arr=ref(['我是字符串'])template里的用法
<button @click="conter++">{{conter}}</button>
<div v-for="item in arr">
<p>{{item}}</p>
</div>js里的用法
function add(){
conter.value++
console.log(conter)
arr.value.push('耗子尾汁')
}獲取虛擬dom (注意:1、變量名稱要和html的一致。2、注意生命周期,要實例創(chuàng)建完成才有虛擬dom)
//html
<div ref="box"></div>
//script
<script setup>
import { ref , onMounted} from "vue";
let box=ref(null)
onMounted(()=>{
console.log(box)
))
</script>到此這篇關(guān)于vue3中使用ref語法糖的文章就介紹到這了,更多相關(guān)vue3 ref語法糖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3+elementPlus項目支持設(shè)置默認(rèn)附件方式
這篇文章主要介紹了vue3+elementPlus項目支持設(shè)置默認(rèn)附件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
在vue中實現(xiàn)表單驗證碼與滑動驗證功能的代碼詳解
在Web應(yīng)用程序中,表單驗證碼和滑動驗證是常見的安全機(jī)制,用于防止惡意攻擊和機(jī)器人攻擊,本文將介紹如何使用Vue和vue-verify-code庫來實現(xiàn)表單驗證碼和滑動驗證功能,需要的朋友可以參考下2023-06-06
vue實現(xiàn)對highlight-current-row方式整行選中后修改默認(rèn)背景顏色
這篇文章主要介紹了vue實現(xiàn)對highlight-current-row方式整行選中后修改默認(rèn)背景顏色方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

