我知道这里已经以不同的形式提出了很多要求,但我很难让孩子对父母所做的改变有所反应。我已经尝试过更改密钥,但是在这种情况下似乎不起作用。
子组件不知道在接收的道具发生更改时会重新渲染吗?
例如(这不是我的确切组件,只是数据流的一个示例):
<template>
<div id="parent">
<h1>Sort By</h1>
<button @click"handleClick('alpha')">Alphabetical</button>
<button @click"handleClick('price')">Price</button>
<ChildComponent :sortBy="sortBy" :key="keyChangingDoesntWork" /> // doesn't update when 'sortBy' changes.
</div>
</template>
<script>
// ...
name: "parent",
data(){
return{
sortBy: 'alpha',
}
},
methods: {
handleClick(by){
if (by === 'alpha') {
this.sortBy = 'alpha'
} else {
this.sortBy = 'price'
}
}
}
</script>
//孩子
<script>
props: {
sortBy: String
}
updated() {
console.log(this.sortBy); // need this to change when buttons are clicked in parent
}
</script>
答案 0 :(得分:1)
您可以观看以下道具
父母:
<template>
<div id="parent">
<h1>Sort By</h1>
<button @click="handleClick('alpha')">Alphabetical</button>
<button @click="handleClick('price')">Price</button>
<ChildComponent v-bind:sortBy="sortBy" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent';
export default {
name: "parent",
data() {
return {
sortBy: 'alpha',
keyChangingDoesntWork: 1
}
},
components: {
'ChildComponent': ChildComponent
},
methods: {
handleClick(by) {
if (by === 'alpha') {
this.sortBy = 'alpha'
} else {
this.sortBy = 'price'
}
return this.sortBy;
}
},
}
</script>
孩子:
<template>
<div>
<h5>Child: {{ sortBy }}</h5>
</div>
<!-- prop change watch-->
</template>
<script>
export default {
props: {
sortBy: String,
},
watch: {
sortBy: function (newVal, oldVal) {
// watch it
console.log("Prop changed: ", newVal, " | was: ", oldVal);
},
},
};
</script>