Vue ref属性 && props配置项

2023-06-12,,

 1 // #    ref属性
2 // # 1.用来给元素或者子组件注册引用信息(id的替代者)
3 // # 2.应用在html标签上获取的是真实的DOM元素,应用在组件标签上是组件实例对象(vc)
4 // # 3.使用方法:
5 // # 打标识:<h1 ref="title">....</h1>
6 // # 获取:console.log(this.$refs.title);
7
8 <template>
9 <div>
10 <h1 v-text="msg" ref="title"></h1>
11 <button @click="showDOM" ref="btn">点我显示上面h1的DOM</button>
12 <School ref="school"></School>
13 </div>
14 </template>
15
16 <script>
17 import School from './components/School.vue'
18
19 export default {
20 name: 'App',
21 components:{
22 School,
23 },
24 data(){
25 return {
26 msg: 'hello'
27 }
28 },
29 methods:{
30 showDOM(e){
31 console.log(this.$refs.title); // 真实DOM元素
32 console.log(this.$refs.btn); // 真实DOM元素
33 console.log(this.$refs.school); // School组件的实例对象
34 }
35 }
36 }
37 </script>
38
39 <style scoped>
40
41 </style>
 1 // 配置项props
2 // 功能:让组件接受外部传过来的数据
3 // 1.传递数据:<Demo name="xxx" />
4 // 2.接受数据:
5 // .第一种方式(只接受):props:['name']
6 // .第二种方式(限制类型):props:{name: String}
7 // .第三种方式(限定类型、限制必填、指定默认值):props:{name: {type:String,required:true,default:'zhangsan'}}
8 // 备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请赋值props的内容到data中一份,然后去修改data中的数据
9 <template>
10 <div class="school">
11 <h1>这里是{{msg}}信息</h1>
12 <h3>名字:{{name}}</h3> <br />
13 <h3>性别:{{sex}}</h3> <br />
14 <h3>年龄:{{myAge+1}}</h3> <br />
15 <button @click="addAgeOne">点我年龄+1</button>
16 </div>
17 </template>
18
19 <script>
20 export default {
21 name: 'School',
22 data(){
23 return {
24 msg: '学生',
25 // name: 'Tony',
26 // sex: 'man',
27 myAge: this.age
28 }
29 },
30 // props:['name', 'age', 'sex'],
31 // props:{
32 // name: String,
33 // age: Number,
34 // sex: String
35 // },
36 props:{
37 name:{
38 type:String,
39 required: true,
40 },
41 age:{
42 type:Number,
43 default: 99
44 },
45 sex:{
46 type:String,
47 required:true
48 }
49 },
50 methods:{
51 addAgeOne(e) {
52 this.myAge++;
53 console.log('addAgeOne');
54 }
55 }
56
57 }
58 </script>
59
60 <style scoped>
61 .school{
62 background-color: orange;
63 }
64 </style>

Vue ref属性 && props配置项的相关教程结束。

《Vue ref属性 && props配置项.doc》

下载本文的Word格式文档,以方便收藏与打印。