0
点赞
收藏
分享

微信扫一扫

Vue学习之--------脚手架的分析、Ref属性、Props配置(2022/7/28)


欢迎大家加入我的社区社区中不定时发红包

文章目录

  • ​​1、脚手架的分析​​
  • ​​2、ref属性​​
  • ​​2.1 基础知识​​
  • ​​2.2 代码实现​​
  • ​​2.3 测试效果​​
  • ​​3、Props配置​​
  • ​​3.1 基础知识​​
  • ​​3.2 代码实例​​
  • ​​3.3 测试效果​​

1、脚手架的分析

├── node_modules
├── public
│ ├── favicon.ico: 页签图标
│ └── index.html: 主页面
├── src
│ ├── assets: 存放静态资源
│ │ └── logo.png
│ │── component: 存放组件
│ │ └── HelloWorld.vue
│ │── App.vue: 汇总所有组件
│ │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件

2、ref属性

2.1 基础知识

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

2.2 代码实现

友情提示:这是关键部分的代码

<template>
<div>
<Student ref="stu"></Student>
<hr />
<h1 v-text="msg" ref="title"></h1>
<button ref="btn" @click="showInfo">展示DOM元素</button>
</div>
</template>

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

export default {
name: "App",
data() {
return {
msg: "我是脚手架",
};
},
methods: {
showInfo() {
console.log(this.$refs.title);//真实DOM元素
console.log(this.$refs.btn);//真实DOM元素
console.log(this.$refs.stu);//组件的实例对象
},
},
components: {
School,
Student,
},
};
</script>

2.3 测试效果

Vue学习之--------脚手架的分析、Ref属性、Props配置(2022/7/28)_数据

3、Props配置

3.1 基础知识

  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中的数据。

3.2 代码实例

编写一个学生的组件、数据展示动态。不再是固定写法

<template>
<div>
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<h2>学生年龄:{{ studentAge }}</h2>
<button @click="modifiAge">修改学生年龄</button>
</div>
</template>

<script>export default {
name: "Student",
data() {
return {
studentAge: this.age,
};
},
methods: {
modifiAge() {
this.studentAge++;
},
},

//简单声明接收
// props:['name','age','sex']

//接收的同时对数据进行类型限制
/* props:{
name:String,
age:Number,
sex:String
} */

props: {
name: {
type: String, //name的类型是字符串
required: true, //name是必要的
},
age: {
type: Number,
default: 99, //默认值
},
sex: {
type: String,
required: true,
},
},
};</script>

<template>
<div>
<Student name="张三" sex="男" :age="18" />
<hr />
</div>
</template>

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

export default {
name: "App",

components: {
School,
Student,
},
};</script>

3.3 测试效果

Vue学习之--------脚手架的分析、Ref属性、Props配置(2022/7/28)_默认值_02


Vue学习之--------脚手架的分析、Ref属性、Props配置(2022/7/28)_默认值_03


Vue学习之--------脚手架的分析、Ref属性、Props配置(2022/7/28)_学习_04


举报

相关推荐

0 条评论