Computed value modification/style dynamic binding/v-for struct decomposition assignment/watch multiple variables in watch

eg(Example 5. Check the rendered result)


1. Modify the value of computed

To modify the value of computed, we use a setter

<script setup>
import { ref, computed } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
fullName.value = 'John Doe' // modify the value of computed (call setter)

const fullName = computed({
  // getter
  get() {
    return firstName.value + ' ' + lastName.value
  },
  // setter
  set(newValue) {
    // Notes: Using decomposition assignment syntax.
    [firstName.value, lastName.value] = newValue.split(' ')
  }
})
</script>

References


2.Style Dynamic Binding

{ style name : value } , [ inline-style ] format dynamically applies style (similar to class dynamic binding)

const fontColor = 'color:red'
const size = 15
...
<div :style="[fontColor,{fontSize:size+'px'}]">test</div>

References


Example of using 3.v-for for structured assignment of items

Basically, { } allows for structured assignment

When using ( ), you are using index

const items = ref([{ message: 'Foo' }, { message: 'Bar' }])

*** Common v-for usage examples
<li v-for="item in items">
  {{ item.message }}
</li>

*** Structure decomposition assignment1
<li v-for="{ message } in items">
  {{ message }}
</li>

*** Decomposition assignment 2
<!-- If index alias is also used -->
<li v-for="({ message }, index) in items">
  {{ message }} {{ index }}
</li>




4. Watching multiple variables with watch

You can watch for changes by passing (function, array, variable, etc.) as the first argument

const x = ref(0)
const y = ref(0)

// Watch a single variable
watch(x, (newX) => {
  console.log(`x value: ${newX}`)
})

// Watch multiple variables (watch the calculated result)
// Pass a getter function as the first argument and watch the result of x.value + y.value
watch(
  () => x.value + y.value, // first argument (getter function)
  (sum) => { // second argument (setter function)
    console.log(`x + y: ${sum}`)
  }
)

// Watching multiple variables (using an array)
// Pass an array as the first argument to watch the result of x and y
watch([x, () => y.value], ([newX, newY]) => {
  console.log(`x is ${newX}, y is ${newY}.
})

References


5. Child components are automatically set to the root element of the child when style, class, and event are entered as attributes of the child component in the parent template


Parent template

<Child component @click="event1" style="color:red" class="test-class1">


ChildComponent

<button @click="Event2" style="width:100px" class="test-class2" /> 


Actual rendered result (check attached image)

<button @click="Event1,Event2" style="color:Red; width:100px; " class="test-class1 test-class2" />

Reference

May 18, 2024 Views 105