父子组件传值

119 阅读1分钟

父向子:v-bind方式,子组件要接收

子向父:$emit方式,向上一层触发事件,子组件触发,父组件监听,监听过后实现传值功能

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>todolist</title>
    <title>Document</title>
    <script src="./vue.js"></script>
</head>

<body>
    <div id="app">
        <input type="text" v-model="inputValue">
        <!-- v-model实现数据双向绑定 -->
        <button v-on:click="handleBtnClick">提交</button>
        <!--v-on给button绑定click事件 -->
        <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'], //props定义外部传递数据
            template: "<li v-on:click = 'handleItemClick'>{{content}}</li>",
            methods: {
                handleItemClick: function () {
                    this.$emit("delete", this.index);
                }
            }
        }

        // vue实例
        var app = new Vue({
            el: '#app',
            //局部组件注册
            components: {
                TodoItem: TodoItem
            },
            data: {
                list: [],
                inputValue: ''
            },
            methods: {
                handleBtnClick: function () {
                    this.list.push(this.inputValue) //获取data里的inputValue,放入list数组
                    this.inputValue = '' //清除input框里的内容
                },
                handleItemDelete: function (index) {
                    this.list.splice(index, 1)
                }
            }
        })
    </script>
</body>

</html>