gpt4 book ai didi

javascript - vue.js:根据 API 响应动态添加复选框的 react 列表

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:08 26 4
gpt4 key购买 nike

我有一个 vue.js 组件,其中包含一个查询 Google Places API 的搜索字段(为简单起见,已将其删除)。响应是包含地点的列表复选框。当用户检查某个地点时,我想在所选对象上将标记 checked 设置为 true

但是,我也想使该属性成为响应式属性,但在运行时添加响应式属性不起作用(请参阅 https://vuejs.org/guide/reactivity.html )。

<template>
<form>
<input type="text" ref="complete" v-bind:placeholder="placeholder">
<fieldset v-if="places" class="checklist">
<h4>Select your store locations:</h4>
<div v-for="place in places">
<input :id="place.id" type="checkbox" v-model="place.checked">
<label :for="place.id">
{{ place.name }}<br>
<span class="subtext">{{ place.formatted_address }}</span>
</label>
</div>
</fieldset>
</form>
</template>
<script>
export default {
data() {
return {
places: [],
api: {
domain: 'https://maps.googleapis.com/maps/api/js',
key: 'API Key',
libraries: 'places',
},
};
},
mounted() {
window.onload = this.loadScript(
`${this.api.domain}?key=${this.api.key}&libraries=${this.api.libraries}`,
this.bindAutocomplete
);
},
watch: {
},
methods: {
loadScript(src, callback) {
const script = document.createElement('script');
document.body.appendChild(script);
if (callback) {
script.onload = callback;
}
script.src = src;
},
bindAutocomplete() {
this.autocomplete = new google.maps.places.SearchBox(
this.$refs.complete
);
this.autocomplete.addListener('places_changed', this.pipeAddress);
},
pipeAddress() {
this.places = this.autocomplete.getPlaces();
},
},
};
</script>

该组件可以工作,但我无法以编程方式将任何复选框设置为“已选中”,例如通过 this.places.forEach((place) => { place.checked = true; }。实现此目标的正确方法是什么?

谢谢

亨宁

最佳答案

您需要在观察数据之前(即在将数据添加到data之前)声明checked属性。

实现此目的的一种方法是在分配之前将 getPlaces() 返回的数组中的 places 对象转换为包含 checked 属性到 data 中的键。

pipeAddress() {
this.places = this.autocomplete.getPlaces().map(
place => { place.checked = false; return place }
);
},

现在,当观察到数据时,checked 属性将出现并因此具有反应性,因此 DOM 可以相应更新。

Here's a fiddle

Explanation来自 Vue 博客:

When you are adding a new property that wasn’t present when the data was observed. Due to the limitation of ES5 and to ensure consistent behavior across browsers, Vue.js cannot detect property addition/deletions. The best practice is to always declare properties that need to be reactive upfront. In cases where you absolutely need to add or delete properties at runtime, use the global Vue.set or Vue.delete methods.

关于javascript - vue.js:根据 API 响应动态添加复选框的 react 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123135/

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