vue 父子组件传值
2.7
以下代码需要到vue官网下载vue.js引入方可运行 https://cn.vuejs.org/js/vue.js
一、父组件向子组件传值:
父组件向子组件通过v-bind的形式来进行数据的传递,子组件通过props来接收(代码中黄色背景标识为父组件向子组件传值核心代码)
二、子组件向父组件传值
子组件向父组件传值,通过$emit的方式向上一层触发事件,子组件触发的事件父组件通过监听就能获取到子组件带出来的内容,实现
子组件向父组件传值(代码中紫色背景标识为子组件向父组件传值核心代码)
//v-bind 简写 :
//v-on 简写 @
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>hello world</title> <script src="vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button v-on:click="handleClick">提交</button> <ul> <todo-item :content='item' :index='index' v-for="(item,index) in list" @delete = 'handleItemDelete' > </todo-item> </ul> </div> <script> var TodoItem = { props:['content','index'], template:"<li @click='handleItemClick'>{{content}}</li>", methods:{ handleItemClick:function(){ this.$emit('delete',this.index) } } } var app = new Vue({ el: "#app", components:{ TodoItem }, data: { list:[], inputValue:"" }, methods:{ handleClick: function(){ this.list.push(this.inputValue); this.inputValue = "" console.log(this.inputValue) }, handleItemDelete:function(index){ this.list.splice(index,1) console.log(index) } } }) </script> </body> </html>