Rumah > hujung hadapan web > tutorial js > Lembaran Penipuan Vue The Dark Side | Kereaktifan Bahagian

Lembaran Penipuan Vue The Dark Side | Kereaktifan Bahagian

Susan Sarandon
Lepaskan: 2024-10-02 08:17:02
asal
698 orang telah melayarinya

Hai DEV.kepada komuniti!

Artikel ini akan merangkumi berbilang aspek Vue 3 yang kebanyakannya digunakan atau agak gelap dan tidak diberi perhatian seperti yang sepatutnya.

Semasa saya akan menerangkan Vue 3, saya akan menggunakan API komposisi dan bukan API pilihan sekolah lama. Konsep kedua-dua kaedah adalah sama supaya anda boleh menyesuaikan diri dengan API komposisi dengan cepat. Saya tidak berada di tempat untuk menentukan apa-apa dan setiap pengaturcara bebas memilih cara mereka mahu menulis program mereka tetapi sebagai pendapat peribadi, saya lebih suka API komposisi untuk sintaksnya yang ringkas dan pengurusan kod yang lebih baik. Jadi jika anda masih takut untuk menukar kepada API komposisi, saya cadangkan anda mencubanya kerana ia berbaloi.

Vue  Cheat Sheet of The Dark Side | Part  Reactivity

Beginilah perasaan anda selepas membaca artikel ini. Saya harap :).

Jadual Kandungan

  • Kereaktifan
    • Ruj
    • Reaktif
    • Ruj Cetek
    • Reaktif Cetek
    • Reaktif Cetek
    • Baca sahaja
    • Baca Cetek Sahaja
  • Dikira
    • Dikira Boleh Tulis
  • Menonton
    • Tonton
      • Segera
      • Sekali
      • Fungsi Menonton Getter
      • Menonton Pelbagai Nilai
    • Kesan Tonton

Kereaktifan

React bukanlah satu-satunya yang perlu diingat apabila kita bercakap tentang kereaktifan. Kereaktifan merujuk kepada keupayaan entiti (diberikan halaman web) untuk bertindak balas berdasarkan perubahan data. Anda mungkin tahu konsep ini sebagai MVVM. MVVM ialah bentuk singkatan Model-View-View-Model. Seperti namanya apabila data berubah, paparan berubah dan begitu juga sebaliknya.

Untuk menggunakan kuasa kereaktifan Vue terdapat beberapa pilihan yang akan kami bincangkan.

Ruj

Anda boleh menganggap ref sebagai jenis pembolehubah istimewa yang boleh anda gunakan dalam aplikasi Vue anda. Perihalan ini hanya benar apabila anda mula bekerja dengan Vue buat kali pertama kerana ia menjadi lebih kompleks selepas itu.

Mentakrifkan rujukan adalah semudah ini:

const message = ref("Hello World")
Salin selepas log masuk

Gunakannya di dalam templat anda menggunakan sintaks interpolasi:

<span>{{ message }}</span>
Salin selepas log masuk

Jika anda bertanya kepada diri sendiri mengapa saya memanggilnya pembolehubah tetapi mengisytiharkan mesej menggunakan kata kunci const, anda mempunyai hak untuk melakukannya.

Seperti yang anda tahu, anda tidak boleh menukar nilai pemalar, kerana ia adalah tujuan kata kunci const. Tetapi ada perkara kecil yang perlu anda ketahui. Walaupun kata kunci const tidak membenarkan data pembolehubah ditukar, ia tidak mengambil berat tentang data bersarang! Ini juga berlaku dengan ref. Untuk memahami situasi ini dengan lebih baik cuba kod di bawah:

const o = {
  a: 1,
  b: 2,
  c: 3
}
console.log(o.a) // 1
o.a = 4
console.log(o.a) // 4
Salin selepas log masuk

Seperti yang anda lihat, saya boleh menukar nilai o.a kerana objek hanyalah rujukan dan bukan nilai keseluruhan dengan sendirinya. Oleh itu, apabila saya menukar nilai dalam objek o had const tidak digunakan. Sudah tentu, jika anda ingin memberikan nilai kepada o sendiri, ia akan menimbulkan ralat dan tidak akan membenarkan anda melakukannya. Contohnya, kod di bawah adalah salah:

const o = {
  a: 1,
  b: 2,
  c: 3
}
o = "hello"
Salin selepas log masuk

Ini adalah kes yang sama apabila menggunakan ref (dan perkara lain yang anda akan lihat nanti di sini). Apabila anda menggunakan fungsi ref ia menukar semua yang diterima menjadi objek. Ini dipanggil membungkus. Cuba kod ini:

const message = ref("Hello World")
console.log(message)
Salin selepas log masuk

Anda sepatutnya melihat sesuatu seperti imej di bawah:

Vue  Cheat Sheet of The Dark Side | Part  Reactivity

Seperti yang anda boleh lihat semasa mengelog pembolehubah mesej anda tidak menerima Hello World secara langsung, sebaliknya ia berada di dalam objek dan anda boleh mengakses nilai sebenar anda menggunakan kekunci nilai objek yang disebutkan di atas. Ini membolehkan Vue melihat perubahan dan melakukan perkara MVVM! :)

Apabila anda mengakses rujukan anda di dalam templat Vue, anda tidak perlu mengaksesnya seperti message.value. Vue cukup pintar untuk memberikan nilai sebenar di dalam templat dan bukannya objek. Tetapi sekiranya anda ingin mengakses atau mengubah suai nilai rujukan di dalam skrip anda, anda harus berbuat demikian menggunakan .value:

message.value = "Adnan!"
console.log(message.value) // Adnan!
Salin selepas log masuk

Reaktif

Seperti yang anda lihat semasa menggunakan ref, Vue membungkus data anda di dalam objek dan membolehkan anda mengaksesnya melalui .value. Ini biasanya kes yang paling banyak digunakan. Anda boleh membungkus hampir semua perkara menggunakan ref dan menjadikannya reaktif.

Sekiranya anda tertanya-tanya bagaimana Vue melihat perubahan nilai dan memaparkan paparan berulang kali, anda harus menyemak Proksi JavaScript.

Jika nilai anda ialah objek itu sendiri, maka anda boleh menggunakan reaktif dan bukannya ref. Fungsi reaktif tidak akan membalut nilai anda dan sebaliknya akan menjadikan objek itu sendiri reaktif dan boleh ditonton.

const o = reactive({count: 0})
Salin selepas log masuk

Jika anda cuba mencetak pemalar o, anda akan melihat bahawa ia sememangnya objek anda tanpa sebarang perubahan besar:

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++
}
Salin selepas log masuk

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

const o = ref({count: 0})

const increase = () => {
    o.value.count++
}
Salin selepas log masuk

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'
  }
})
Salin selepas log masuk

And printed my last name in your template as below:

<span>{{ state.names.adnan }}</span>
Salin selepas log masuk

If you every changed my last name like this:

state.value.names.adnan = 'masruri'
Salin selepas log masuk

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'
})
Salin selepas log masuk

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'
    }
  }
})
Salin selepas log masuk

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'
})
Salin selepas log masuk

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)
})
Salin selepas log masuk

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>
Salin selepas log masuk

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'
})
Salin selepas log masuk

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'
})
Salin selepas log masuk

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'
})
Salin selepas log masuk

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)
Salin selepas log masuk

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
  }
})
Salin selepas log masuk

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

fullName.value = 'Ata Parvin'
Salin selepas log masuk

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)
})
Salin selepas log masuk

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)
})
Salin selepas log masuk

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,
})
Salin selepas log masuk

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,
})
Salin selepas log masuk

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>
Salin selepas log masuk

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>
Salin selepas log masuk

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)
})
Salin selepas log masuk

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.

Atas ialah kandungan terperinci Lembaran Penipuan Vue The Dark Side | Kereaktifan Bahagian. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan