vue.js实战笔记:父子组件之间的那些事儿

来源:互联网 发布:开票软件 含税价标志 编辑:程序博客网 时间:2024/05/29 07:24

父组件向子组件传递数据


父组件向子组件传递数据:
栗子1:父组件A向子组件A-1传递参数:currStudentId,有两种传递方式:


第一种传递方式,是使用静态传递方式,打个比方A-1组件中,需要的是一个固定的值,常量,那么,可以使用这种传递方式,语法:

//子组件A-1Vue.component('A-1', {  // 声明 props  props: ['currStudentId'],  data: function() {        return {            page: 1        }    }  // 就像 data 一样,prop 可以用在模板内  template: '<span>{{ currStudentId }}</span>'})//父组件A<A-1 curr-student-id='1'></A-1>

需注意,这里使用curr-student-id而不能使用currStudentId,因为VUE规定:
HTML 特性是不区分大小写的。所以,当使用的不是字符串模版,camelCased (驼峰式) 命名的 prop 需要转换为相对应的 kebab-case (短横线隔开式) 命名


第二种传递方式,是使用动态传递方式,和静态传递方式不同,我们要传递的是非固定的值。

//子组件A-1Vue.component('A-1', {  // 声明 props  props: ['currStudentId'],  data: function() {        return {            page: 1        }    }  // 就像 data 一样,prop 可以用在模板内  template: '<span v-model="currStudentId"></span>'})//父组件A中使用A-1组件<A-1 :curr-student-id='studentId'></A-1>

子组件向父组件传递数据(改变父组件数据)


//子组件A-1Vue.component('A-1', {  // 声明 props  props: ['currStudent'],  data: function() {        return {            page: 1        }    },    methods: {        changeStudent: function() {            this.currStudent.name="xyz";        }    }})
//父组件A<A-1 curr-student='currStudent'></A-1>父组件中A中data数据格式如下:data() {    return {        currStudent: {            name: ''        }    }}

在vue2.0之后的版本中,不允许子组件直接改变父组件的数据,在1.0的版本中可以这样操作的,但是往往项目需求需要改变父组件的数据,2.0也是可一个,区别是,当我们把父元素的数据给子组件时,需要传一个对象,子组件通过访问对象中的属性操作数据


父组件操作子组件的方法

//子组件A-1:Vue.component('A-1', {  // 声明 props  props: ['currStudentId'],  data: function() {        return {            page: 1        }    }  // 就像 data 一样,prop 可以用在模板内  template: '<span v-model="currStudentId"></span>',  methods: {      showStudents() {          console.info("students");      }  }})
//父组件<A-1 :curr-student-id='studentId' ref="studentComponent"></A-1>this.$refs.studentComponent.showStudents();

子组件和父组件监听事件

栗子:子组件A-1触发父组件A。


//子组件A-1Vue.component('A-1', {  data: function() {        return {            page: 1,            student: ''        }    }  // 就像 data 一样,prop 可以用在模板内  template: '<span v-model="currStudentId"></span>',  methods: {    studentPick: function() {        //$emit触发        this.$emit('set-student', this.student);    }  }})
//父组件A中添加监听<A-1 @set-student="setStudent"></A-1>//父组件中添加方法setStudentmethods: {    //.......other methods    setStudent: function(studentInfo){        //studentInfo是自组件触发传过来的    }}
原创粉丝点击