首頁 > web前端 > js教程 > Vue 黑暗面備忘錄 |部分反應性

Vue 黑暗面備忘錄 |部分反應性

Susan Sarandon
發布: 2024-10-02 08:17:02
原創
699 人瀏覽過

DEV.社區大家好!

本文將包括 Vue 3 的多個方面,這些方面大多被使用,或者有點陰暗,但沒有像他們應該的那樣受到關注。

當我要描述 Vue 3 時,我將使用組合 API,而不是老式的選項 API。兩種方法的概念是相同的,因此您可以快速適應組合 API。我無權規定任何事情,每個程式設計師都可以自由選擇他們想要編寫程式的方式,但作為個人觀點,我更喜歡組合 API,因為它簡潔的語法和更好的程式碼管理。因此,如果您仍然害怕更改組合 API,我建議您嘗試一下,因為這是值得的。

Vue  Cheat Sheet of The Dark Side | Part  Reactivity

這就是你讀完這篇文章後的感受。我希望:)。

目錄

  • 反應性
    • 參考
    • 反應性
    • 淺參考
    • 淺反應
    • 淺反應
    • 唯讀
    • 淺唯讀
  • 計算的
    • 可寫入計算
  • 觀看
    • 手錶
      • 立即
      • 一次
      • 觀看 Getter 函數
      • 觀察多個值
    • 觀看效果

反應性

當我們談論反應性時,React 並不是唯一應該想到的。反應性是指實體(給定網頁)根據資料變化做出反應的能力。您可能知道這個概念為 MVVM。 MVVM 是模型-視圖-視圖-模型的縮寫形式。顧名思義,當資料更改時視圖也會更改,反之亦然。

為了利用 Vue 的反應能力,我們將介紹一些選項。

參考號

您可以將 ref 視為一種特殊類型的變量,您可以在 Vue 應用程式中使用它。只有當您第一次開始使用 Vue 時,此描述才正確,因為之後它會變得更加複雜。

定義 ref 就這麼簡單:

const message = ref("Hello World")
登入後複製

使用插值語法在模板中使用它:

<span>{{ message }}</span>
登入後複製

如果您問自己為什麼我將其稱為變數但使用 const 關鍵字聲明訊息,您完全有權這樣做。

如您所知,您無法更改常數的值,因為這是 const 關鍵字的用途。但有一些微妙的小事情你應該知道。雖然關鍵字 const 不允許更改變數的數據,但它並不關心嵌套數據! ref 也是如此。為了更好地理解這種情況,請嘗試以下程式碼:

const o = {
  a: 1,
  b: 2,
  c: 3
}
console.log(o.a) // 1
o.a = 4
console.log(o.a) // 4
登入後複製

如您所見,我可以更改 o.a 的值,因為物件只是引用,而不是其本身的完整值。因此,當我更改物件內部 a 的值時,不會套用 const 限制。當然,如果你想給 o 本身賦值,它會拋出一個錯誤並且不會讓你這樣做。例如,下面的程式碼是錯誤的:

const o = {
  a: 1,
  b: 2,
  c: 3
}
o = "hello"
登入後複製

使用 ref 時的情況相同(以及稍後您將在此處看到的其他內容)。當您呼叫 ref 函數時,它會將收到的所有內容轉換為物件。這稱為包裹。試試這個程式碼:

const message = ref("Hello World")
console.log(message)
登入後複製

您應該看到如下圖的內容:

Vue  Cheat Sheet of The Dark Side | Part  Reactivity

如您在記錄訊息變數時所看到的,您沒有直接接收Hello World,而是它位於一個物件內部,您可以使用上述物件的值鍵來存取您的實際值。這讓 Vue 可以觀察變化並執行 MVVM 的操作! :)

當您在 Vue 範本中存取 ref 時,無需像 message.value 那樣存取它。 Vue 足夠智能,可以渲染模板內的實際值而不是物件。但如果您想存取或修改腳本中 ref 的值,您應該使用 .value:

message.value = "Adnan!"
console.log(message.value) // Adnan!
登入後複製

反應性

如您在使用 ref 時所見,Vue 將您的資料包裝在一個物件內,並允許您透過 .value 存取它。這通常是最常用的情況。您可以使用 ref 包裝幾乎所有內容並使其具有響應性。

如果您想知道 Vue 如何監視值變化並一次又一次地渲染視圖,您應該查看 JavaScript 代理程式。

如果你的值本身就是一個對象,那麼你可以使用reactive而不是ref。響應式函數不會包裝您的值,而是使物件本身俱有響應式且可觀看。

const o = reactive({count: 0})
登入後複製

如果你嘗試列印 o 常數,你會發現它確實是你的對象,沒有任何重大變化:

Vue  Cheat Sheet of The Dark Side | Part  Reactivity

Now you may manipulate the key count as you would normally do in JavaScript and Vue will render the changes as soon as possible.

Here is an example:

const increase = () => {
    o.count++
}
登入後複製

If you had ref instead of reactive it would have looked like this:

const o = ref({count: 0})

const increase = () => {
    o.value.count++
}
登入後複製

If you are still unsure which one to use, keep in mind that ref is a safe option to use.

Shallow Ref

Give that you have a ref like below:

const state = ref({
  names: {
    adnan: 'babakan',
    arian: 'amini',
    ata: 'parvin',
    mahdi: 'salehi'
  }
})
登入後複製

And printed my last name in your template as below:

<span>{{ state.names.adnan }}</span>
登入後複製

If you every changed my last name like this:

state.value.names.adnan = 'masruri'
登入後複製

Your template will be updated to show masruri instead of babakan. This is due to the fact that ref makes a deeply watched object and the changes to the view (template) are triggered for nested data as well.

There is an option to prevent such behaviour if that's what you want. To do so you may use shallowRef. A shallowRef acts exactly like ref does, with an exception of not watching for deep changes.

const state = shallowRef({
  names: {
    adnan: 'babakan',
    arian: 'amini',
    ata: 'parvin',
    mahdi: 'salehi'
  }
})

onMounted(() => {
  state.value.names.adnan = 'masruri'
})
登入後複製

The code above will result in your template showing babakan as it is not watched. But changing the .value entirely will trigger changes. So the code below will result in your template getting updated as well:

const state = shallowRef({
  names: {
    adnan: 'babakan',
    arian: 'amini',
    ata: 'parvin',
    mahdi: 'salehi'
  }
})

onMounted(() => {
  state.value = {
    names: {
      adnan: 'masruri',
      arian: 'amini',
      ata: 'parvin',
      mahdi: 'salehi'
    }
  }
})
登入後複製

This is a great option for performance-related concerns.

Shallow Reactive

So far we've known that ref wraps the data and watches it deeply and shallowRef wraps the data and watches it shallowly. Now tell me this, if reactive makes an object reactive, what does shallowReactive do?

const state = shallowReactive({
  names: {
    adnan: 'babakan',
    arian: 'amini',
    ata: 'parvin',
    mahdi: 'salehi',
  },
})

onMounted(() => {
  state.names.adnan = 'masruri'
})
登入後複製

As you might have guessed the template won't be updated.

Trigger Ref

Given that you are using a shallowRef and changed a value and now want your template to be updated according to the new data as well, you may use the triggerRef function:

const state = shallowRef({
  names: {
    adnan: 'babakan',
    arian: 'amini',
    ata: 'parvin',
    mahdi: 'salehi'
  }
})

onMounted(() => {
  state.value.names.adnan = 'masruri'
  triggerRef(state)
})
登入後複製

Now the template will also show masruri. This is more like changing from an automatic gear to a manual gear if you will.

This is usable for both shallowRef and shallowReactive.

Read Only

The readonly function receives a ref or a reactive as an argument and returns an exact copy that is only possible to be read from. This is used when you want to make sure your data is safe and is not possible to change when watching for it.

Example:

<template>
  <div>
    {{ infoReadOnly }}
  </div>
</template>

<script setup>
const info = ref({
  first: 'Adnan',
  last: 'Babakan'
})

const infoReadOnly = readonly(info)

onMounted(() => {
  info.value.first = 'Arian'
})
</script>
登入後複製

Though I've changed the value of info, since infoReadOnly is actually a live copy of info my changes are reflected in infoReadOnly as well. Yet you may not change the values using infoReadOnly directly:

const info = ref({
  first: 'Adnan',
  last: 'Babakan'
})

const infoReadOnly = readonly(info)

onMounted(() => {
  infoReadOnly.value.first = 'Arian'
})
登入後複製

This won't change the data and will warn you in the console as below:

Vue  Cheat Sheet of The Dark Side | Part  Reactivity

Shallow Read Only

If we have ref and shallowRef, reactive and shallowReactive, why not have a shallowReadonly?

A shallowReadonly only makes the root level elements readonly whilst you can change the nested data:

const stateShallowReadonly = shallowReadonly({
  name: 'Adnan',
  friends: [
    { name: 'Arian' },
    { name: 'Ata' },
    { name: 'Mahdi' }
  ]
})

onMounted(() => {
  stateShallowReadonly.name = 'Brad'
})
登入後複製

The code above will warn you and won't change the value of name since it is a direct property.

But you can freely change anything inside friends since it is nested:

const stateShallowReadonly = shallowReadonly({
  name: 'Adnan',
  friends: [
    { name: 'Arian' },
    { name: 'Ata' },
    { name: 'Mahdi' }
  ]
})

onMounted(() => {
  stateShallowReadonly.friends[0].name = 'Brad'
})
登入後複製

Computed

Man, I love computed in Vue! You can imagine it as a glass in which you can mix your potions and still have your potions standing there intact!

A computed is like a ref or reactive that can be accessed and watched but not changed. Then what's the difference between a computed and a readonly you might ask. A computed can be a mixture of stuff. For example:

const state = ref({
  first: 'Adnan',
  last: 'Babakan'
})

const fullName = computed(() => state.value.first + ' ' + state.value.last)
登入後複製

Now you have a fullName which you may access its value inside a template with {{ fullName }} or inside your script using fullName.value.

The value of fullName will always depend on the state.value.first and state.value.last and will change if those guys change.

A computed receives a function that returns a value and can depend on multiple reactive data.

Writable Computed

Though a computed is mostly used to read a combination of data, the possibility to make a computed writable is also there.

Instead of passing a function to computed you may pass an object including two properties called get and set that both are functions.

For instance:

const state = ref({
  first: 'Adnan',
  last: 'Babakan'
})

const fullName = computed({
  get: () => state.value.first + ' ' + state.value.last,
  set: (value) => {
    const [first, last] = value.split(' ')
    state.value.first = first
    state.value.last = last
  }
})
登入後複製

Now if you try to write the value of fullName like below:

fullName.value = 'Ata Parvin'
登入後複製

It will split your string into 2 parts using a space and assign the first part to state.value.first and the second to state.value.last.

This is not a good way to determine which part of a name is a first name and which is a last name, but for the sake of demonstration, this is the only thing that came to my mind. :D

Watching

Watching is something that you will probably need a lot. Watching is referred to the act in which you want to run something in case a reactive data changes. In different systems there are various naming for this act, sometimes they are called hooks as well. But in Vue, we will call them watches.

Watch

The first thing you will encounter. A watch function receives two arguments. The reactive data to watch and the function to be invoked when the data changes respectively.

Here is a simple watch:

const count = ref(0)

const increase = () => {
  count.value++
}

watch(count, () => {
  console.log('Count changed to ' + count.value)
})
登入後複製

Now whenever the value of count is changed, you will see the log Count changed to ((count)) in your console.

The callback function also receives two arguments which are passed to it when the watch is triggered. The first argument holds the new value and the second one holds the old value. Here is an example:

const count = ref(0)

const increase = () => {
  count.value++
}

watch(count, (newValue, oldValue) => {
  console.log('Counter changed from ' + oldValue + ' to ' + newValue)
})
登入後複製

Note: Be careful when using the newValue and oldValue with objects as objects are passed by reference.

To be more accurate, a watch function receives a third argument as well. This third argument is an object that holds some options which can change the behaviour of the watching action.

Immediate

An immediate watch function is triggered at the instance it's created as well as when a change happens. You can think of it as the difference between a while loop and a do...while loop if you know what I mean. In other words, even if there is never a change, your callback function will run at least once:

watch(count, () => {
  console.log('Count changed to ' + count.value)
}, {
  immediate: true,
})
登入後複製

The value for immediate can be true or false. And the default value is false.

Once

If you want your watcher to run only once, you may define the once option and set its value to true. The default value is false.

watch(count, () => {
  console.log('Count changed to ' + count.value)
}, {
  once: true,
})
登入後複製

This will only trigger once when the value of count changes.

Advanced Watchers

Previously we've mentioned that watchers accept a reactive data as the first argument. While this is true, this is not the whole case.

A watch function can receive a getter function or an array of reactive objects and getter functions. This is used for when we need to watch for multiple data changes, and/or when we need to watch the result of two or more things when affecting each other. Let's have some examples.

Watching Getter Function

Take the code below as an example:

<template>
  <div>
    <div>
      <div>Timer one: {{ timerOne }}</div>
      <div>Timer two: {{ timerTwo }}</div>
    </div>
    <button @click="timerOne++">Accelerate timer one</button>
    <button @click="timerTwo++">Accelerate timer two</button>
  </div>
</template>

<script setup>
const timerOne = ref(0)
const timerTwo = ref(0)

onMounted(() => {
  setInterval(() => {
    timerOne.value++
    timerTwo.value++
  }, 1000)
})

watch(() => timerOne.value - timerTwo.value, () => {
  console.log('There was a change in the gap between timerOne and timerTwo. Gap is ' + (Math.abs(timerOne.value - timerTwo.value)) + ' seconds.')
})
</script>
登入後複製

It's a simple code that makes 2 refs holding a number and increasing both of them 1 by 1 each second. Logically the difference of these two refs are always equal to zero unless one gets changes out of its turn. As both increase the difference stays 0 so the watched won't get triggered as it only watches for the changes to the result of timerOne.value - timerTwo.value.

Yet there are two buttons that each adds 1 to timerOne and timerTwo respectively. When you click on any of those buttons the difference will be more or less than 0 thus the watch being triggered and logging the gap between these two timers.

Watching Multiple Values

Here is an example of an array of reactive data being passed to the first argument of the watch function:

<template>
  <div>
    <div>
      <div>Counter one: {{ counterOne }}</div>
      <div>Counter two: {{ counterTwo }}</div>
    </div>
    <button @click="counterOne++">Increase counter one</button>
    <button @click="counterTwo++">Increase counter two</button>
  </div>
</template>

<script setup>
const counterOne = ref(0)
const counterTwo = ref(0)

watch([
  counterOne,
  counterTwo,
], () => {
  console.log('One of the counters changes')
})
</script>
登入後複製

No matter which ref changes, the watcher will be triggered.

Watch Effect

A watchEffect function acts almost exactly like a watch function with a main difference. In a watchEffect you don't need to define what to watch and any reactive data that is used inside the callback you provide your watchEffect is watched automatically. For example:

const count = ref(0)

watchEffect(() => {
  console.log(count.value)
})
登入後複製

In case our count is changed the watchEffect will trigger its callback function since count.value is used inside it. This is good if you have complex logic to watch for.


Hope this was useful and you've enjoyed it. In case you spot any mistakes or feel like there should be an improvement, kindly let me know.


BTW! Check out my free Node.js Essentials E-book here:

Feel free to contact me if you have any questions or suggestions.

以上是Vue 黑暗面備忘錄 |部分反應性的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板