子组件的按钮触发事件中$emit,且除emit的信号名外只能带一个参数。多余的参数需要用字典型传参。
<el-button v-on:click="cancel">取 消</el-button> <el-button v-on:click="submit" type="primary" :disabled="state.username_valid===false">确 定</el-button> methods: { cancel:function(){ this.$emit('hidedialog'); }, submit:function(){ var dict = {title:this.title, message:this.message, username:this.username}; this.$emit("newmessage", dict); this.$emit("hidedialog"); } },首先定义methods,在methods中修改自身data里的数据:
data(){ return { messageList: [], dialogVisible: true, } }, methods: { hidedialog:function(){ this.dialogVisible = false; // 改了data }, newmessage:function (dict){ var timestamp = new Date().getTime(); var item = {title:dict.title, content:dict.message, user:dict.username, timestamp:timestamp}; this.messageList.push(item); // 改了data } }然后在父组件中的子组件<>内用v-on绑定信号(就是on-click改成on-xxx):
<MessageList v-bind:message-list="messageList"/> <PostDialog v-on:hidedialog="hidedialog" v-on:newmessage="newmessage" v-bind:dialog-visible="dialogVisible"/>最后用v-bind把父组件中改好的data传给子组件对应的props,如上一段代码。
子组件PostDialog.vue中:
props: { dialogVisible: { type: Boolean, default: () => true },子组件MessageList中:
props: { messageList: { type: Array, default: () => new Array(5).fill({ title: "Hello", content: "Hello World!", user: "unknown", timestamp: new Date().getTime() }) } }这些default内容都会被替换成从父组件中传入的内容。