javascript - Vue.js mounted function not accessing component properties -
i'm not new vue.js why feel i've been running mad morning :). while creating component, do, quite frequently, in case, had initialize google maps within mounted
function, seems right place that. in mounted
function, access id
property of nested input field , attach event listener it. pretty simple right?
well, figured when try use component multiple times on page, i'm somehow accessing same (seemingly shared) this
variable within mounted
function.
not sure why happens and/or if it's feature make weirder, props yield correct values within template. (and within methods well)
component definition
<template> <div class="locationinput"> <input type="text" :id="id" /> </div> </template> <script> export default { name: 'locationinput', props: ['id'], mounted() { console.log('component object representation ==> ', this) console.log('id ==> ', this.id) } } </script>
using component...
<template> <div class="mytravelapp"> <locationinput id="id1"/> <locationinput id="id2"/> </div> </template> <script> import locationinput './components/locationinput'; export default { components: { locationinput } } </script>
what @ end of day correct id values in template in console, exact same object , id logged can see below. notice how _uid
property same thing both.
to make matters worse, after modifying this
variable in mounted
function, while inspecting, observed second component has property modified well. sharing same object, extremely weird.
i know if has had similar issues , how deal it.
no self-closing tags components.
vue templates need valid html. there no "self closing tags" in html5, it's xhtml syntax outdated , should never use it.
(later note:)
fyi self-closing tags works in 2.0 long don't use in-dom templates.
you may having issue camelcase vs. kebab-case. snippet below behaves expected.
vue.component('locationinput', { template: '#location-input-template', props: ['id'], mounted() { console.log('component object representation ==> ', this._uid) console.log('id ==> ', this.id) } }); new vue({ el: '#my-travel-app' });
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script> <template id="location-input-template"> <div class="locationinput"> <input type="text" :id="id"> </div> </template> <div id="my-travel-app"> <location-input id="id1"></location-input> <location-input id="id2"></location-input> </div>
Comments
Post a Comment