简体   繁体   中英

how to get dynamic data into array and append it to dom vue.js

I want to append my the data that i clicked, but I get the same output as undefined.

<template>
<aside> 
    <ul>
        <li v-for="link in links" > </li>
           <button @click="tabLinks" v-text="link.textName" >  </button>
        </li>
    </ul>
</aside>
</template>

this is my script file

export default {
    data(){
        return {
         links : [
            {textName: 'Link 1',icon: 'fa-user fa'},
            {textName: 'link 2',icon: 'fa-search fa'},
            {textName: 'link 3',icon: 'fa-thrash fa'}
            ],
        }
    },
    methods: {
        tabLinks(){
            this.links.push({textName: this.textName  })
        }
    }
}

There are few errors in your code.

For example in the method tabLinks , you are pushing an object, but this.textName is not passed, it will not take automatically as you clicked on that button, one option can be to pass it ini the method.

In your HTML, you have closed </li> twice.

You can see these rectification and working code here: https://fiddle.jshell.net/mimani/x6ndwj8u/1/

Modified HTML :

<ul>
  <li v-for="link in links">
    <button @click="tabLinks(link.textName)">{{link.textName}}</button>
  </li>
</ul>

Updated method:

  methods: {
    tabLinks(textName) {
      this.links.push({
        textName: textName
      })
    }
  }

Your html structure is incorrect. There is a redundant </li> tag

<aside> 
    <ul>
        <li v-for="link in links" > </li> <-- remove this
           <button @click="tabLinks" v-text="link.textName" >  </button>
        </li>
    </ul>
</aside>

also this will not work

this.links.push({ textName: this.textName  })

because there is no this.textName . I'm not sure what you are trying to do, maybe you will want to pass a parameter to your tabLinks method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM