简体   繁体   中英

Insert Vue.js JSON object value directly into a Javascript setInterval function

How can I input a Vue.js object for the current item into another Javascript function on the page?

I have a slide HTML page that only displays the current HTML ID

Each slide I have has a time in seconds pulled in from my JSON, the timer object. I need to put this number in seconds into a SetInterval function to load programmatically the next slide.

var seconds = parseInt(document.querySelector("#value").innerText) * 1000;
      setInterval(function () {
          document.querySelector("a.o-controls2").click();
      }, seconds)

You can see the example in action here .

I have tried loading the expression value but get a null result in the console. So perhaps this has something to do with the page load and how Vue renders the page?

I have also tried the following, by loading in the Vue object but this didn't work either:

var seconds = (this.timer - 1) 1000;
setInterval(function () { document.querySelector("a.o-controls2").click();
}, seconds)

The null response is the return from querySelector() ; it's returning null because the external script is running before Vue has rendered the application. When the script runs, there is no element with an id of "value" in the document.

The easiest fix might be to move that code into the mounted() lifecycle hook of the app; possibly within a nextTick() to make sure that all child components have also rendered.

the easiest way (IMHO) to access the data after some change (in this case, after fetch ) is to use $emit and $on

this.items = items.reverse();
this.$nextTick(() => this.$emit('dataLoaded', this.items));

you could also use it without the nextTick, but then you'd get the data back before the dom is updated, so your js would fail.

this.items = items.reverse();
this.$emit('dataLoaded', this.items);

then listen to the change using...

app.$on('dataLoaded', items => {
  console.log('items', items)
  document.querySelector("a.o-controls2"); // now accessible
  // do stuff
})

here is a fiddle: https://jsfiddle.net/y32hnzug/1/ it doesn't implement the click timing though since that's outside the scope of the question

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