1

How do I access an element from within the mounted function in a VueJS instance.

When I try the following, it tells me that the element is undefined. When I see the DOM it is there. Could this be a case where the element is not rendered before I try to reference it?

document.getElementsByName('transferDate_submit')[0].addEventListener("change",function(){});
MontyTheMack
  • 331
  • 1
  • 5
  • 13
  • Can you give more code? dom should be able to be referred in mounted function, see my sample: https://jsfiddle.net/choasia/qb7cr912/ – choasia Aug 02 '17 at 00:46

2 Answers2

1

You get a HTMLElement instance when you call your Vue.js instance with $el. Check the API.

Example

let allLinks = this.$el.querySelectorAll('a')

Alternatively, you could use a ref. This is a like a programmatic ID. Also check the API.

Example

<!-- vm.$refs.p will be the DOM node -->
<p ref="p">hello</p>
tony19
  • 125,647
  • 18
  • 229
  • 307
Julian
  • 1,380
  • 12
  • 28
0

You can just use v-on:change or @change to bind your event listener so that you can avoid manipulating DOM element. Besides, Vue.js is to make you not to DOM as far as possible

Sea Monster
  • 141
  • 1
  • 6
  • The element is being dynamically generated by a JavaScript plugin I am using. I want to use the value from the input field that is generated but need to add a change event listener to do that – MontyTheMack Aug 02 '17 at 00:49
  • `var app = new Vue({ el: '#app', data: { }, mounted() { console.log(this.el.getElementsByName('transferDate_submit')); function test() { console.log("This is a change event"); } document.getElementsByName('transferDate_submit')[0].addEventListener("change", test.bind(this)); } });` Removed data for confidentiality purposes – MontyTheMack Aug 02 '17 at 00:55
  • Well, I would like to make the element as a template, and bind the function to this element. I recommend vue-cli to construct your project :) – Sea Monster Aug 02 '17 at 01:02