gpt4 book ai didi

javascript - Vue.js 挂载函数不访问组件属性

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:44 25 4
gpt4 key购买 nike

我对 Vue.js 不是很陌生,这可能就是为什么我觉得我整个上午都在发疯 :)。在创建组件时,我经常这样做,在这种情况下,我必须在 mounted 函数中初始化 Google map ,这似乎是执行此操作的正确位置。在 mounted 函数中,我将访问嵌套输入字段的 id 属性并将事件监听器附加到它。很简单吧?

好吧,我发现当我尝试在我的页面上多次使用该组件时,我以某种方式访问​​了 mounted 中的相同(看似共享的)this 变量> 功能。

不确定为什么会发生这种情况和/或它是否是一项功能,但更奇怪的是, Prop 在模板中产生正确的值。 (以及在方法中)

组件定义

<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 属性对两者来说是一样的。

Console Output

更糟糕的是,在修改 mounted 函数中的 this 变量后,在检查时,我观察到第二个组件也修改了该属性。所以他们本质上共享同一个对象,这非常奇怪。

我想知道有没有人遇到过类似的问题以及如何处理。

最佳答案

No self-closing tags for components .

Vue templates need to be valid HTML. There are no "self closing tags"in HTML5, it's an XHTML syntax which is now outdated and you shouldnever use it.

(后记:)

FYI self-closing tags works in 2.0 as long as you don't use in-domtemplates.

您可能还遇到了 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'
});
<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>

关于javascript - Vue.js 挂载函数不访问组件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43413588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com