通过props向子组件传递数据 在子组件中,使用props来声明幼从父级接收到的数据。 props可以是字符串数组、可以是对象。 子组件
//1、当数据类型为对象或数组是默认值要返回一个对象或数组 //child1 props: { cpn: { type: Object, default(){ return {} } }, }, //child2 props:{ cpn:{ type:Array, default(){ return []; } } }, //也可以不指定默认值 //child3 props: { cpn1: String, cpn2: { type: String, default: "red", }, },父组件
import child1 from './~' import child1 from './~' import child1 from './~' components: { child1, child2, child3 }, data(){ return{ arr: [1,2,3], obj:{name:'zlw',age:21} } } //动态添加使用了**:**语法糖 <child1 :cpn="arr" /> <child2 :cpn="obj" /> //直接赋值 <child3 cpn1="/home" cpn2="blue">**需要使用自定义事件 e m i t ∗ ∗ 在 子 组 件 中 通 过 emit** 在子组件中通过 emit∗∗在子组件中通过emit()来触发事件,在父组件中通过v-on来监听事件
//child <div @click="itemClick(index)">触发事件</div> methods:{ itemClick(index){ this.currentIndex = index this.$emit('tabClick',index) } } //parent //import。注册组件此处省略。 <child @tabClick="tabClick" /> //此处的@tabClick的事件名必须要与子组件发送的事件名一致 methods: { /** * 事件监听相关的方法 */ tabClick(index) { switch (index) { case 0: this.currentType = "pop"; break; case 1: this.currentType = "new"; break; case 2: this.currentType = "sell"; break; } },