gpt4 book ai didi

vue.js - 从父组件重置子组件的形式

转载 作者:搜寻专家 更新时间:2023-10-30 22:25:12 25 4
gpt4 key购买 nike

我有一个父组件和一个子组件。子组件位于父组件的对话框内。并且显示或隐藏此对话框。

我的父组件

<template>
<div>
<v-dialog v-model="dialog">
<product-form></product-form>
</v-dialog>
</div>
</template>

我的子组件(产品形式)

<template>
<div>
.....
<input type="text" v-model="data">
.....
</div>
</template>
<script>
export default {

data: () => ({
data: '',
}),
methods:{

onSubmitProduct(){

//send data to server
}
},
}
</script>

每当显示对话框时,我都需要清除子窗体。问题是我通过父组件显示对话框。注意:我不想在子组件中使用 v-model,因为我需要将数据从子组件而不是父组件发送到服务器。

有人可以帮助我吗?

* **解决方案 ***

我能够使用 ref 解决问题。我不知道我的解决方案是否违反了良好做法。但这是我能做的最好的。

//parent component
<template>
<div>
<v-dialog v-model="dialog">
<product-form ref="childComponent"></product-form>
</v-dialog>
</div>
</template>

this.$refs.childComponent.resetForm();

-

//child compopnent
<template>
<div>
.....
<input type="text" v-model="data">
.....
</div>
</template>
<script>
export default {

data: () => ({
data: '',
}),
methods:{

onSubmitProduct(){

//send data to server
},
resetForm(){
//code to reset form
}
},
}
</script>

最佳答案

您可能应该让一辆公共(public)汽车作为给 child 的 Prop 。然后您可以发出一个事件, child 可以根据该事件采取行动。

new Vue({
el: '#app',
data: {
showing: false,
bus: new Vue()
},
methods: {
toggleDialog() {
this.showing = !this.showing;
this.bus.$emit('reset');
}
},
components: {
productForm: {
template: '#product-form-template',
props: ['bus'],
data() {
return {
value: 'you will never see this'
}
},
methods: {
resetForm() {
this.value = 'Form was reset';
}
},
created() {
this.bus.$on('reset', this.resetForm);
}
}
}
});
.dialog {
outline: 2px solid blue;
height: 200px;
}
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<button @click="toggleDialog">Toggle dialog</button>
<div class="dialog" v-show="showing">
<product-form :bus="bus"></product-form>
</div>
</div>

<template id="product-form-template">
<div>
Type something here: <input v-model="value">
</div>
</template>

关于vue.js - 从父组件重置子组件的形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48933321/

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