[英]Vue.js update parent data with an input from a child component
I'm using Vue.js 2 and I'm trying to update the description of a file using an input in a child component.我正在使用 Vue.js 2 并尝试使用子组件中的输入来更新文件的描述。 I've been reading a few related questions and read some of the official docs along with .sync but I'm struggling to get the result I want since files is a list of objects.我一直在阅读一些相关问题并阅读一些官方文档以及.sync但我正在努力获得我想要的结果,因为文件是一个对象列表。
Here's what I've been trying.这就是我一直在尝试的。
Vue.component('myComponent', { props: ["file"], data() { return { myDescription: '', } }, mounted() { this.myDescription = this.file.description; }, template: ` <div> <label>{{ file.name }}</label> <br> <input type="text" @input="update":value="myDescription"></input> <br><br> </div> `, methods: { update() { this.$emit("update-description", this.myDescription, this.file); }, } }) var app = new Vue({ el: '#app', methods: { updateDescription(description, file) { console.log(description); } }, data: { files: [{ id: 1, name: "Hello", description: "", }, { id: 2, name: "World", description: "Foo", }, { id: 3, name: "John", description: "Bar", } ] } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div> {{ files }} </div> <br> <my-component v-for="file in files":key="file.id":file="file" @update-description="updateDescription" /> </div>
You're almost there, you can see in the code you've provided that the child component event is being emitted but the value is empty.您快完成了,您可以在提供的代码中看到正在发出子组件事件,但值为空。 The problem is you're not updating myDescription
, if you change your :value
to v-model
then it will update, as v-model
uses two way binding.问题是您没有更新myDescription
,如果您将:value
更改为v-model
那么它将更新,因为v-model
使用双向绑定。
Also, if you want to update the file description, you can just do:另外,如果你想更新文件描述,你可以这样做:
file.description = description;
Vue.component('myComponent', { props: ["file"], data() { return { myDescription: '', } }, mounted() { this.myDescription = this.file.description; }, template: ` <div> <label>{{ file.name }}</label> <br> <input type="text" @input="update" v-model="myDescription"></input> <br><br> </div> `, methods: { update() { this.$emit("update-description", this.myDescription, this.file); }, } }) var app = new Vue({ el: '#app', methods: { updateDescription(description, file) { console.log(description); file.description = description; } }, data: { files: [{ id: 1, name: "Hello", description: "", }, { id: 2, name: "World", description: "Foo", }, { id: 3, name: "John", description: "Bar", } ] } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div> {{ files }} </div> <br> <my-component v-for="file in files":key="file.id":file="file" @update-description="updateDescription" /> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.