vue(props与$emit)

164 阅读1分钟

1、父组件可以使用 props 把数据传给子组件。 2、子组件可以使用 $emit 触发父组件的自定义事件。

vm.$emit( event, arg ) //触发当前实例上的事件

vm.$on( event, fn );//监听event事件后运行 fn;

  <div id="app">
        <zz-searcher aa='bb' tip="zzz" style=" width:500px" @search="zz"></zz-searcher>
        <zz-searcher tip="sxsxsx"></zz-searcher>
        <zz-searcher></zz-searcher>
    </div>
    </div>

css代码:

   <style>
        * {
            margin: 0;
            padding: 0;

        }

        .searcher {
            display: flex;
            border: 1px grey solid;
            width: 300px;
            height: 30px;
            margin: 200px;
        }

        .icon{
            background: url(https://img3.doubanio.com/f/sns/f71f15922ebd7c0ff0ea0e7a25577529efd8981a/pics/icon/bn_srh_1.png) no-repeat center;
            width: 30px;
            height: 30px;
            cursor: pointer;
        }

        .searcher input {
            flex: 1;
            border: none;
            text-indent: 10px;
            outline: none;
        }
    </style>

js代码:

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>

        Vue.component("zz-searcher", {
            props:['tip','aa'],
            data(){
                return{
                    keywords:""
                }
            },
           
            methods: {
                search(){
                    this.$emit("search",this.keywords);
                    // console.log(this.keywords)
                }
            },
            template:`
            <div class="searcher">
            <input type="text" :placeholder="tip" v-model="keywords">
            <div class="icon" @click="search"></div>
                
            </div>`
        })
        let vm = new Vue({
            el:"#app",
            data(){
                return{

                }
            },
            methods: {
                zz(e){
                    console.log(e)
                }
            },
        })
    </script>