todo-vue 蔚落 2023-05-30 10:52 26阅读 0赞 主要是父子间通讯和方法调用 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>todo-vue</title> <script src="js/vue.js" type="text/javascript" charset="utf-8"></script> <script src="https://cdn.jsdelivr.net/npm/vue"></script> </head> <body> <div id="app"> <todo> <!--slot插槽. 通过:xx=''的方式向子组件传值(通讯) 通过@xx=''来传递方法,$event接收this.$emit()的第一个参数 --> <title-slot slot="title-slot" :title='title' @add="addMessage($event)"></title-slot> <!--父子组件通讯时 :xx @xx 名称是自定义的--> <li-slot slot="li-slot" v-for="(message,index) in messageList" :key='index' :message='message' :index='index' @remove="removeMessage($event)"></li-slot> </todo> </div> <script> //定义组件:有2个插槽,相当于占位符 Vue.component('todo',{ template:"<div>\ <slot name='title-slot'></slot>\ <ul>\ <slot name='li-slot'></slot>\ </ul>\ </div>\ " }), //定义组件: props接收父组件传递的属性. this.$emit('add',this.message)调用父组件的方法 Vue.component('title-slot',{ props:['title'], template:"<span>{ {title}}:<input v-model='message'/><button type=\"button\" @click='addMessage'>添加</button></span>", data(){ return{ message:'' } }, methods:{ addMessage() { this.$emit('add',this.message) } } }), //定义组件: remove()实际调用的是父组件的删除方法 Vue.component('li-slot',{ props:['message','index'], template:'<li>{ {message}} <button @click="remove(index)">删除</button><li>', methods:{ remove(index){ this.$emit('remove',index) } } }) var vm = new Vue({ el:'#app', data(){ return{ messageList:['吃饭','代码','撩妹','睡觉'], title: '添加备忘录' } }, methods:{ removeMessage(index){ this.messageList.splice(index,1) }, addMessage(message) { this.messageList.push(message) } } }) </script> </body> </html>
还没有评论,来说两句吧...