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

父组件向子组件传递数据


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


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

//子组件A-1
Vue.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-1
Vue.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-1
Vue.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-1
Vue.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>

//父组件中添加方法setStudent
methods: {
    //.......other methods
    setStudent: function(studentInfo){
        //studentInfo是自组件触发传过来的
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值