美文网首页
VUE 父子组件互相传值

VUE 父子组件互相传值

作者: MccReeee | 来源:发表于2019-02-09 09:45 被阅读11次

    父组件代码

    var app = new Vue({
            el: "#root",
            components: {
                TodoItem: TodoItem,
            },
            data: {
                todoValue: "",
                list: []
            },
            methods: {
                handleBtnClick: function () {
                    this.list.push(this.todoValue)
                    //添加完后清空输入框
                    this.todoValue = ""
                },
                handleItemDelete: function (index) {
                    this.list.splice(index, 1)
                }
            }
        })
    

    子组件代码

    //这是局部组件的写法
        var TodoItem = {
            props: ["content", "index"],
            template: "<li @click='handleItemClick'> {{content}}</li>",
            methods: {
                handleItemClick: function () {
                    this.$emit("delete", this.index)
                }
            }
        }
    
    • 父组件向子组件传值 通过v-bind:
    <todo-item 
    v-bind:content="item" 
    v-bind:index="index" 
    v-for="(item,index) in list"
    @delete="handleItemDelete">
    </todo-item>
    
    • 子组件向父组件传值 通过事件绑定,比如这个@delete=handleItemDelete,并在父组件中实现handleItemDelete
    this.$emit("delete", this.index)
    
    methods: {
                handleBtnClick: function () {
                    this.list.push(this.todoValue)
                    //添加完后清空输入框
                    this.todoValue = ""
                },
                handleItemDelete: function (index) {
                    this.list.splice(index, 1)
                }
            }
    

    相关文章

      网友评论

          本文标题:VUE 父子组件互相传值

          本文链接:https://www.haomeiwen.com/subject/lsuasqtx.html