vue父子组件传值例子

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue 入门</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

</head>
<body>

    <div id="app">
        <div>
            <input type="text" v-model="inputValue">
            <button @click="add">提交</button>
        </div>
        <ul>
            <todo-item
                v-for="(item,index) in list"
                :content="item"
                :key="index"
                :index="index"
                @delete="del"
            > 
            </todo-item>
            <!-- 子组件要传递值到父组件 通过 this.$emit传递一个事件到父组件 父组件触发
            后 再触发父组件的方法,delete事件就是中间事件 handelclick子组件的点击  del父组件的点击 -->
            <!-- <li v-for="(item,index) in list" :key="index" @dblclick="handelClick"> {{ item }}</li> -->
        </ul>
    </div>
    <script>
        Vue.component('todo-item',{
            props:['content','index'],
            template:"<li @dblclick='handelClick'>{{content}}</li>",
            methods:{
                handelClick(){
                    this.$emit('delete',this.index)
                }
            }
        })

        new Vue({
            el:"#app",
            data:{
                inputValue:'',
                list:[]
            },
            methods:{
                add() {
                    this.list.push(this.inputValue)
                    this.inputValue = ''
                },
                del(index){
                    this.list.splice(index,1)
                }
            }
            
           
        })
    
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/php-linux/p/11617371.html