我对Vue.js不是很新,这可能就是为什么我觉得我整个上午都疯了:)。在创建一个组件时,我经常这样做,在这种情况下,我不得不在mounted
函数中初始化Google地图,这似乎是正确的地方。在mounted
函数中,我将访问嵌套输入字段的id
属性并将事件侦听器附加到它。很简单吧?
好吧,我想当我尝试在我的页面上多次使用该组件时,我会以某种方式访问this
函数中的相同(看似共享的)mounted
变量。 / p>
不确定为什么会发生这种情况和/或如果它是一个功能但是为了使它更奇怪,道具会在模板中产生正确的值。 (以及在方法中)
组件定义
<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>
使用我的组件......
<template>
<div class="MyTravelApp">
<LocationInput id="id1"/>
<LocationInput id="id2"/>
</div>
</template>
<script>
import LocationInput from './components/LocationInput';
export default {
components: { LocationInput }
}
</script>
我在一天结束时得到的是模板中正确的id值,但在我的控制台中,会记录完全相同的对象和id,如下所示。注意_uid
属性对于两者都是一样的。
更糟糕的是,在修改this
函数中的mounted
变量后,在检查时,我发现第二个组件也修改了该属性。所以他们基本上是共享同一个对象,这非常奇怪。
我想知道是否有人遇到过类似问题以及如何解决这个问题。
答案 0 :(得分:0)
No self-closing tags for components
Vue模板必须是有效的HTML。没有&#34;自闭标签&#34; 在HTML5中,它是一个XHTML语法,现在已经过时了,你应该这样做 永远不要使用它。
(后来注意:)
只要您不使用in-dom,FYI自动关闭标签就可以在2.0中运行 模板。
您可能也遇到camelCase vs. kebab-case的问题。下面的代码片段符合预期。
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'
});
&#13;
<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>
&#13;