一、data—数据区域
- 类型:Function,返回组件实例的 data 对象的函数。
- 存放数据区域
二、props—传值区域
- 类型:Array | Object
- props 可以是数组或对象,用于接收来自父组件的数据。props 可以是简单的数组,或者使用对象作为替代,对象允许配置高阶选项,如类型检测、自定义验证和设置默认值。
- type:可以是下列原生构造函数中的一种:String、Number、Boolean、Array、Object、Date、Function、Symbol、任何自定义构造函数、或上述内容组成的数组。会检查一个 prop 是否是给定的类型,否则抛出警告。Prop 类型的更多信息在此。
- default:any 为该 prop 指定一个默认值。
- required:Boolean 义该 prop 是否是必填项。
- validator:Function 自定义验证函数会将该 prop 的值作为唯一的参数代入。在非生产环境下,如果该函数返回一个 false的值 (也就是验证失败),一个控制台警告将会被抛出。你可以在这里查阅更多 prop 验证的相关信息。
三、computed—计算区域
- 类型:{ [key: string]: Function | { get: Function, set: Function } }
- 计算属性将被混入到组件实例中。所有 getter 和 setter 的 this 上下文自动地绑定为组件实例。
- 注意,如果你为一个计算属性使用了箭头函数,则 this 不会指向这个组件的实例,不过你仍然可以将其实例作为函数的第一个参数来访问。
四、methods—方法区域
- 类型:{ [key: string]: Function }
- methods 将被混入到组件实例中。可以直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为组件实例。
- 注意,不应该使用箭头函数来定义 method 函数 (例如 plus:() => this.a++)。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向组件实例,this.a 将是 undefined。
五、watch—监听区域
- 类型:{ [key: string]: string | Function | Object | Array}
- 一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。
- 注意,不应该使用箭头函数来定义 watcher 函数 (例如 searchQuery: newValue => this.updateAutocomplete(newValue))。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向组件实例,this.updateAutocomplete 将是 undefined。
<div id="compon">
组件
{{msg}}
<button @click="changeMsg">修改数据</button>
<button @click="changeCount">count++</button>
{{count}}
<!-- 挂载一个小的子组件 -->
<!-- 组件传值--静态传值 -->
<child title="标题" content="我是内容"></child>
<!-- 组件传值--动态传值 -->
<child :title="title" :content="content" :num="price"></child>
</div>
//写的时候常规方法
import child from './components/child'
export default{
name:"compon",
components:{
child
},
data() {
return {
//数据区域
msg:"Hello",
num:0,
title:"商家信息",
content:"商家详细信息",
price:999.999
}
},
methods: {
//方法区域
changeMsg(){
this.msg="world";
},
changeCount(){
this.count++;
}
},
computed:{
//计算属性区域
//类似变量的声明,是监听变量的,也可以缓存之前的变量值
// count(){
// //默认只能读取readonly
// return 0;
// }
//若是你既要可写又要可读,就得使用get、set访问器
count:{
get(){
return this.num;
},
set(vm){
this.num=vm;
}
}
},
watch:{
//监听区域
count(newValue,oldValue){
console.log(newValue,oldValue);
}
}
}
<div id="childinfo">
<h4>我是子组件</h4>
<h3>{{title}}</h3>
<h3>{{content}}</h3>
<h2>{{num}}</h2>
</div>
export default{
name:"childinfo",
//props:['title','content'],//简单版的子组件设置传递参数
//props传值存在类型或者默认值的行为
// props:{
// //数据类型限制
// title:String,
// content:String
// }
//检验类型+默认值+检验
props:{
title:String,
content:String,
num:{
type:Number,
default:0,
//检验值
validator(value){
if(value.toString().indexOf('.')!=-1)
{
return false;
}
return true;
}
}
}
}