定义一个父组件app.vue,父组件中有对象query_dict,实现在子组件child1.vue中对query_dict进行增删改查并在app.vue中调用child2.vue以显示实时的query_dict键值对。(请详细注释)
时间: 2024-05-04 07:22:15 浏览: 7
在app.vue中,我们定义了一个对象query_dict,并将其作为prop传递给child1.vue和child2.vue组件。
```html
<template>
<div>
<child1 :query_dict="query_dict" @update-query="updateQuery"></child1>
<child2 :query_dict="query_dict"></child2>
</div>
</template>
<script>
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'
export default {
components: {
Child1,
Child2
},
data() {
return {
query_dict: {}
}
},
methods: {
updateQuery(query) {
this.query_dict = query
}
}
}
</script>
```
在child1.vue中,我们实现了对query_dict的增删改查,并通过$emit触发update-query事件将更新后的query_dict传递回父组件app.vue。
```html
<template>
<div>
<h3>Child1</h3>
<ul>
<li v-for="(value, key) in query_dict" :key="key">
{{ key }}: {{ value }}
<button @click="deleteQuery(key)">删除</button>
</li>
</ul>
<form @submit.prevent="addQuery">
<label>
Key:
<input type="text" v-model="newKey">
</label>
<label>
Value:
<input type="text" v-model="newValue">
</label>
<button type="submit">添加</button>
</form>
<form @submit.prevent="updateQuery">
<label>
Key:
<input type="text" v-model="updateKey">
</label>
<label>
Value:
<input type="text" v-model="updateValue">
</label>
<button type="submit">更新</button>
</form>
</div>
</template>
<script>
export default {
props: ['query_dict'],
data() {
return {
newKey: '',
newValue: '',
updateKey: '',
updateValue: ''
}
},
methods: {
addQuery() {
if (this.newKey && this.newValue) {
this.$set(this.query_dict, this.newKey, this.newValue)
this.newKey = ''
this.newValue = ''
this.$emit('update-query', this.query_dict)
}
},
deleteQuery(key) {
this.$delete(this.query_dict, key)
this.$emit('update-query', this.query_dict)
},
updateQuery() {
if (this.updateKey && this.updateValue) {
this.$set(this.query_dict, this.updateKey, this.updateValue)
this.updateKey = ''
this.updateValue = ''
this.$emit('update-query', this.query_dict)
}
}
}
}
</script>
```
在child2.vue中,我们通过props接收query_dict并展示其中的键值对。
```html
<template>
<div>
<h3>Child2</h3>
<ul>
<li v-for="(value, key) in query_dict" :key="key">
{{ key }}: {{ value }}
</li>
</ul>
</div>
</template>
<script>
export default {
props: ['query_dict']
}
</script>
```