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>demo4</title>
    <script src="https://cdn.bootcss.com/vue/2.4.1/vue.js"></script>

</head>

<body>
<div id="app">
    <search-bar></search-bar>
    <list-bar></list-bar>
</div>

<script>
    //借助一个全局的vue空实例,定义两个方法,一个on一个emit,
    // on即是向回调数组push key 和对应的function,emit就是触发key对应的function
    let tempVm = new Vue();

    let searchBar = {
        template:`
        <div>
            <div>
                <label for="">账户:</label>
                <input type="text" v-model="person.account">
            </div>
            <div>
                <label for="">密码:</label>
                <input type="text" v-model="person.password">
            </div>
            <div>
                <input type="button" value="ok" @click="addItem">
            </div>
        </div>`,
        data(){
            return{
                person:{
                    account:'',
                    password:''
                }
            }
        },
        methods:{
            addItem(){
                tempVm.$emit("onAddItem",{account:this.person.account,password:this.person.password});
                this.person.account = this.person.password = '';
            }
        }
    };

    let listBar = {
        template:`
        <div>
            <div v-for="item in items">
                {{item.account}} ----- {{item.password}}
            </div>
        </div>`,
        data(){
           return{
               items:[]
           }
        },
        created(){
            let _this = this;
            tempVm.$on('onAddItem',function(e){
                _this.items.push(e)
            })
        }
    };

    new Vue({
        el:"#app",
        components:{
            'search-bar':searchBar,
            'list-bar':listBar
        }
    })
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_40285497/article/details/79912359