简体   繁体   中英

Fail to access DOM element in Vue component when using generic javascript

I am trying to dynamic to update data from Vue.compnent by using jQuery way on Webpack project. following is code snippet.

<template>
    <div id="container">
        <slot>show string!!</slot>
        <div id="s_container"></div>
    </div>
</template>

<script>
export default {

}

const items = [
  'thingie',
  'anotehr thingie',
  'lots of stuff',
  'yadda yadda'
]

function listOfStuff () {
  let full_list = ''

  for (let i = 0; i < items.length; i++) {
    full_list = full_list + '<li>{{items[i]}}</li>'
  }
  //  const contain = document.querySelector('#s_container')
  const contain = this.$el.querySelector('#s_container')
  if (contain != null) { 
      contain.innerHTML = '<ul ${full_list} </ul>' 
  } else {
     console.log('contain is null');
  }
}
listOfStuff()
</script>

but this contain variable is always fail to get #s_container element. How can I get it correctly from outside java script? Thanks.

First you need to bind your items array into a data return function like this:

export default {
 data()
  return {
   items: ['thingie', 'yadda yadda']
  }
}

Then you can use a v-for loop the display this array into a HTML li. Like this into your template:

<template>
  <div>
   <ul>
     <li v-for="(item, index) in items" :key=index>
      {{ item }}
     </li>
   </ul>
  </div>
</template>

In this way you can render a simple list using vue.js, if you need more informations about this feature read this part of the documentation: https://v2.vuejs.org/v2/guide/list.html

Have a good day !

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