Home > Software design >  Manipulation HTML DOM of Vue3 List Item
Manipulation HTML DOM of Vue3 List Item

Time:11-10

i use vue 3 and i want to manipulate a single list item by button click

this is my html:

<socialDiv v-for="(follower, i) in followerList" :key="follower.id" :ref="el => { followerDiv[i] = el }">
<div >{{ follower.name }}</div>
<div >{{ follower.username }}</div>
<button @click="handleBtnClick" id="fbtn">{{ follower.btn }}</button>

this is my script:

<script setup>
const followerDiv = ref({})

function handleBtnClick() {
  console.log(followerDiv.value)
}
</script>

this is my output:

enter image description here

i'm able to access followerDiv.value[0] but i cannot manipulate the item itself as a DOM element.

how can i access the child items as DOM elements?

Update:

To access the list items i have to add "$el" after value.

I can access the values via:

followerDiv.value[i].$el.style.background = "red"

CodePudding user response:

If I understood you correctly, you can pass index to your function :

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const followerDiv = ref({})
    const followerList = ref([{id: 1, name: 'aa', username: 'aa', btn: 'aa'}, {id: 2, name: 'bb', username: 'bb', btn: 'bb'}])

    function handleBtnClick(i) {
      followerDiv.value[i].style.color = "red"
    }
    return {
      followerList, followerDiv, handleBtnClick
    }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(follower, i) in followerList" :key="follower.id" :ref="el => { followerDiv[i] = el }">
    <div >{{ follower.name }}</div>
    <div >{{ follower.username }}</div>
    <button @click="handleBtnClick(i)" id="fbtn">{{ follower.btn }}</button>
  </div>
</div>

  • Related