核心提示:父组件向子组件传值:父组件通过v-bind绑定值:p id=appinput type=text v-model=inputValue/button v-on:click=handleBtnClick...
父组件向子组件传值:
父组件通过v-bind绑定值:
<p id="app"> <input type="text" v-model="inputValue"/> <button v-on:click="handleBtnClick">commit</button> <ul> <todo-list :content="item" :index="index" v-for="(item,index) in list" @delete="handleItemDelete"> </todo-list> </ul> </p>
父组件通过v-for遍历list,获得每一个item,:content未v-bind:content的简写,把item的值绑定到content字段传给子组件。
在子组件中通过props接收从父组件传过来的值。
var TodoList = { props: ['content','index'], template: "<li @click='handleItemClick'>{{content}}</li>", methods: { handleItemClick: function() { this.$emit("delete",this.index) } } }
在子组件中通过插值表达式{{}}的方式可以将接收到的content值绑定到<li>标签上。
点击hello ,删除hello
在子组件中通过$emit方法触发事件,如当点击<li>标签时,触发delete事件删除当前的<li>标签:
methods: { handleItemClick: function() { this.$emit("delete",this.index) } }
在父组件中监听delete事件,
<todo-list :content="item" :index="index" v-for="(item,index) in list" @delete="handleItemDelete"> </todo-list>
如果监听到就根据当前的index把item从list中删除:
handleItemDelete: function(index) { this.list.splice(index,1) }