Vue 2.x – ref属性/props配置项

ref属性

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:<h1 ref="xxx">.....</h1>``<School ref="xxx"></School>
    2. 获取:this.$refs.xxx
// App.vue
<template>
  <div>
    <h1 v-text="msg" ref="title"></h1>
    <button ref="btn" @click="showDOM">点我输出上方DOM元素</button>
    <School ref="sch" />
  </div>
</template>

<script>
// 引入School
import School from "./components/School.vue";
export default {
  name: "App",
  components: { School },
  data() {
    return {
      msg: "欢迎学习Vue",
    };
  },
  methods: {
    showDOM() {
      console.log(this.$refs.title); // 正式DOM元素
      console.log(this.$refs.btn);
      console.log(this.$refs.sch); // School组件的实例对象(vc)
    },
  },
};
</script>

props配置项

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

  2. 传递数据:<Demo name="xxx"/>

  3. 接收数据:

    1. 第一种方式(只接收):props:['name']

    2. 第二种方式(限制类型):props:{name:String}

    3. 第三种方式(限制类型、限制必要性、指定默认值):

      props:{
          name:{
          type:String, //类型
          required:true, //必要性
          default:'老王' //默认值
          }
      }

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

// App.vue
<template>
  <div>
    <Student name="李四" sex="女" :age="18" />
    <Student name="王老五" sex="男" :age="29" />
  </div>
</template>

<script>
// 引入School
import Student from "./components/Student.vue";

export default {
  name: "App",
  components: { Student },
};
</script>
// Student.vue
<template>
  <div>
    <h1>{{ msg }}</h1>
    <h2>学生名:{{ name }}</h2>
    <h2>性别:{{ sex }}</h2>
    <h2>年龄:{{ myAge + 1 }}</h2>
    <button @click="updateAge">尝试修改收到的年龄</button>
  </div>
</template>

<script>
export default {
  name: "Student",
  data() {
    return {
      msg: "我是一个学生",
      myAge: this.age,
    };
  },
  methods: {
    updateAge() {
      this.myAge++;
    },
  },
  // props: ["name", "sex", "age"], // 简单接受组件传参
  // 接受的同时对数据进行限制
  // props: {
  //   name: String,
  //   age: Number,
  //   sex: String,
  // },

  // 接受的同时对数据进行限制+默认值限制+必要性限制
  props: {
    name: {
      type: String,
      required: true,
    },
    age: {
      type: Number,
      default: 99,
    },
    sex: {
      type: String,
      required: true,
    },
  },
};
</script>

版权声明:
作者:Ne-21
链接:https://blog.gocos.cn/archives/120.html
来源:云淡风轻
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
Vue 2.x – ref属性/props配置项
ref属性 被用来给元素或子组件注册引用信息(id的替代者) 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc) 使用方式: 打标识……
<<上一篇
下一篇>>