定义一个父组件app.vue,父组件中有对象query_dict,实现在子组件child1.vue中对query_dict进行增删改查并在app.vue中调用child2.vue以显示实时的query_dict键值对
时间: 2024-05-01 17:22:35 浏览: 14
在 app.vue 中,我们可以定义一个对象 query_dict,然后将它作为 prop 传递给 child1.vue 和 child2.vue。
```html
<template>
<div>
<child1 :query_dict="query_dict" @update-query_dict="updateQueryDict"/>
<child2 :query_dict="query_dict"/>
</div>
</template>
<script>
import Child1 from './child1.vue'
import Child2 from './child2.vue'
export default {
components: {
Child1,
Child2
},
data() {
return {
query_dict: {}
}
},
methods: {
updateQueryDict(newDict) {
this.query_dict = newDict
}
}
}
</script>
```
在 child1.vue 中,我们可以通过 props 接收 query_dict,并向父组件发送 update-query_dict 事件来更新 query_dict。
```html
<template>
<div>
<form @submit.prevent="addKeyValuePair">
<input type="text" v-model="key" placeholder="Key"/>
<input type="text" v-model="value" placeholder="Value"/>
<button type="submit">Add</button>
</form>
<ul>
<li v-for="(value, key) in query_dict" :key="key">
{{ key }}: {{ value }}
<button @click="deleteKeyValuePair(key)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['query_dict'],
data() {
return {
key: '',
value: ''
}
},
methods: {
addKeyValuePair() {
this.$emit('update-query_dict', {...this.query_dict, [this.key]: this.value})
this.key = ''
this.value = ''
},
deleteKeyValuePair(key) {
const {[key]: deleted, ...newDict} = this.query_dict
this.$emit('update-query_dict', newDict)
}
}
}
</script>
```
在 child2.vue 中,我们可以通过 props 接收 query_dict 并直接渲染。
```html
<template>
<div>
<h2>Current Query Dict:</h2>
<ul>
<li v-for="(value, key) in query_dict" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['query_dict']
}
</script>
```