【发布时间】:2021-11-04 05:13:24
【问题描述】:
我是使用 VueJS 的新手,我正在尝试弄清楚当父组件中的 props 发生变化时如何更新/重新渲染子组件。
我最初将一个空数组传递给子数组 - 然后,在 Vuex 存储中发送调度后,我将更新的数据传递给数组。我希望在发生这种情况时看到子更新,但没有变化,更新()方法也不会在子内部调用。
父组件:
<template>
<div class="loginPanel">
<div className="col">
<BaseSelect
v-model="this.sourceGroup"
:options="this.groupCodeList"
label="Source Group"
:emit-event="'sourceGroupSelected'"
@sourceGroupSelected="sourceGroupSelected"
/>
</div>
<div className="col mt-4">
<button type="submit">Search</button>
</div>
</div>
</template>
<script>
import BaseSelect from './BaseSelect'
export default {
name: 'SelectSourceGroup',
components: { BaseSelect },
props: {},
data() {
return {
selectedSourceGroup: '',
sourceGroup: '',
groupCodeList: [],
}
},
methods: {
sourceGroupSelected(value) {
console.log(value)
},
},
computed: {
groupCodes() {
return this.$store.state.groupCodes
},
},
created() {
if (!this.$store.state.groupCodes) {
this.$store.dispatch('getAllGroupCodes')
}
},
updated() {
if (this.groupCodeList.length < 1) {
for (const group of this.groupCodes) {
const { group_code, group_name } = group
this.groupCodeList.push({
key: group_code,
val: group_code,
name: group_name,
})
}
}
},
}
</script>
孩子:
<template>
<label v-if="label">{{ label }}</label>
<select class="field" :value="modelValue" @change="onChange($event)">
<option disabled v-if="label" value="">Select a {{ label }}...</option>
<option disabled v-if="!label" value="">Select an option...</option>
<option
v-for="option in this.options"
:value="option.val"
:key="option.key"
:selected="option.val === modelValue"
>
{{ option.name }}
</option>
</select>
</template>
<script>
export default {
props: {
label: {
type: String,
default: '',
},
modelValue: {
type: [String, Number],
default: '',
},
emitEvent: {
type: [String],
},
options: {
type: Array,
required: true,
},
optionLabel: {
type: String,
default: 'Select an option...',
},
},
updated() {
console.log(this.options)
},
methods: {
onChange(event) {
console.log(this.emitEvent)
this.$emit(this.emitEvent, event.target.value)
},
},
}
</script>
读完这里之后我也尝试过使用 Vue.set:Vue prop not updating properly in a child component 但这遇到了同样的问题,孩子没有更新,也没有调用 updated() 函数:
updated() {
if (this.groupCodeList.length < 1) {
for (let x = 0; x < this.groupCodes.length; x++) {
const { group_code, group_name } = this.groupCodes[x]
let ind = x.toString()
this.$set(this.groupCodeList, ind, {
key: group_code,
val: group_code,
name: group_name,
})
}
}
}
【问题讨论】:
标签: javascript vue.js vue-component vuex