$emit的用法是将子组件的内容传递给父组件,包括:数据,方法等。 子组件:
<div class="div1"> <h3>父组件传给子组件的数据:{{index}}</h3> <br/><button @click="selectType">点击子组件</button> </div> <script> data(){ index:'3' } methods:{ selectType(index){ index=this.index;//给方法里面的参数赋值 this.$emit('select',index) //点击子组件中的button按钮,触发select方法,这个方法用来子组件给父组件发射数据,父组件通过select监听并接收参数,后面的index是参数 } } </script>父组件
<div class="div1"> <zujian1 @select="selectIndex"></zujian1><!--selectIndex是接收子组件的数据随便定义的方法,@select是子组件中传过来的,相当于子组件给父组件注册了@select方法,然后selectIndex是重新赋的一个方法名,这个方法名就可以写在父组件的methods中--> </div> <script> components:{zujian1} methods:{ selectIndex(index){ this.active=index//把子组件里方法里面的参数赋值给父组件中的某个参数 }} </script>使父子组件的传递数据的方法更为明显,更容易理解,做个标记
