$refs 获取DOM元素

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx
  4. 注意 : 重复命名前者会被覆盖


    image.png

    $emit 组件自定义事件

  5. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  6. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
  7. 绑定自定义事件

    1. 第一种方式,在父组件中:<Demo @atguigu="test"/><Demo v-on:atguigu="test"/>
    2. 第二种方式,在父组件中:

      1. <Demo ref="demo"/>
      2. ......
      3. mounted(){
      4. this.$refs.xxx.$on('atguigu',回调)
      5. }
    3. 若想让自定义事件只能触发一次,可以使用once修饰符 <Demo @atguigu.once="test"/>

$once方法 this.$refs.xxx.$once('atguigu',回调)

  1. 触发自定义事件this.$emit('atguigu',数据)
  2. 解绑自定义事件(被绑的vc):
    1. this.$off('atguigu') 解绑一个自定义事件
    2. this.$off(['atguigu','demo']) 解绑多个自定义事件
    3. this.$off() 解绑所有的自定义事件*
  3. 组件上也可以绑定原生DOM事件,需要使用native修饰符。
    <Student @click.native="show"/>
  4. 注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数(箭头函数没有this,于是vue会往上一层找 找到vc实例当做this),否则this指向会出问题!

    props 数据验证

  5. 功能:让组件接收外部传过来的数据

  6. 传递数据:<Demo name="xxx"/>
  7. 接收数据:
    1. 第一种方式(只接收):props:['name']
    2. 第二种方式(限制类型):props:{name:String}
    3. 第三种方式(限制类型、限制必要性、指定默认值):
      1. props:{
      2. name:{
      3. type:String, //类型
      4. required:true, //必要性
      5. default:'老王' //默认值
      6. }
      7. }

备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

  1. data() {
  2. return {
  3. myAge:this.age
  4. }
  5. },
  6. methods: {
  7. updateAge(){
  8. this.myAge++
  9. }
  10. },
  11. //简单声明接收
  12. props:['age']

实例

  1. <body>
  2. <div id="app">
  3. <father></father>
  4. </div>
  5. <!-- 父组件 -->
  6. <template id="father">
  7. <div>
  8. <h1>{{name}}</h1>
  9. <!-- son子组件 -->
  10. <son></son>
  11. </div>
  12. </template>
  13. <!-- 子组件 -->
  14. <template id="son">
  15. <div>父级数据:{{parentname}}</div>
  16. </template>
  17. <script type="text/javascript">
  18. Vue.component("father", {
  19. template: "#father",
  20. data: function() {
  21. return {
  22. "name": "张三"
  23. }
  24. },
  25. components: {
  26. "son": {
  27. props: {
  28. "parentname": {
  29. //type不对控制台会报错
  30. type: [String, Number],
  31. //<son></son> 未绑定parentname
  32. default: "123",
  33. }
  34. },
  35. template: "#son"
  36. }
  37. }
  38. });
  39. let app = new Vue({
  40. el: '#app',
  41. });
  42. </script>
  43. </body>