数据选项

  • 数据(Data)选项可接受类型:对象和函数,组件只能使用函数类型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//对象类型
let vm = new Vue(){
el:'#app',
data:{
title:'Vue Projects',
obj:{}
}
}

//函数类型
Vue.component('buttonCounter',{
data(){
return {
counter:1
}
},
template:'<button @click="counter++">clicked {{counter}} times</button>'
})

注意点:Vue会递归的将 data 数据加入响应式系统,但这些数据应该在声明时即存在,也就是说需要在实例中被观察的对象预先在 data 选项中声明。

  • $set,Object.assign 方法为 data 选项动态绑定数据,但是也无法挂载响应式数据到 $data 根节点。
1
2
3
this.$set(this.obj, 'profile', 'This is a Vue App.');

Object.assign(this.obj, {profile: 'This is a Vue App.'});

属性选项

为组件注册动态特性,处理业务间的差异。使代码可以复用相似的应用场景

  • 属性(props)选项可接受类型:数组和对象,用于接收父组件传递过来的参数,并允许为其设置默认值、类型检查和校验规则等。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Vue.component('colorText',{
props:{
text:String,
color:{
type:'String',
default:'#000',
required:true,
validator(value){
return /^#([0-9a-fA-F]{6}|[0-6a-fA-F]{3})$/.test(value)
}
}
},
template:'<span :style="{color: color}">{{text}}</span>'
})

方法选项

不要用箭头函数(=>)声明 methods 中的方法

计算属性

减轻模板上的业务负担,是代码更易维护

//未使用computed

1
2
3
4
5
<div>
<p>{{message}} .&nbsp; 我看到的是车还是猫。</p>
<p>{{message.replace(/\s/g,'')}}</p>
<p>{{message.replace(/\s/g,'').split(' ').reverse().join(' ')}}</p>
</div>
1
2
3
4
5
6
7
8
let vm = new Vue(){
el:'#app',
data(){
return{
message:'Was it a car or a cat i saw'
}
}
}

//使用computed

1
2
3
4
5
<div>
<p>{{message}} .&nbsp; 我看到的是车还是猫。</p>
<p>{{noSpaceMsg}}</p>
<p>{{palindromeMsg}}</p>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let vm = new Vue(){
el:'#app',
data(){
return{
message:'Was it a car or a cat i saw'
}
},
computed:{
noSpaceMsg(){
return this.message.replace(/\s/g,'')
},
palindromeMsg(){
return this.message.replace(/\s/g,'').split(' ').reverse().join(' ')
}
}
}

computed 不能用箭头函数(=>)声明,混入Vue 实例,可以被 this 调用。

侦听属性

为实例添加被观察对象,并在对象被修改时调用自定义方法。
注重于处理数据变化时的业务逻辑。
可以异步修改数据。
丰富的声明方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
watch:{
msg(newVal, oldVal){
this.noSpaceMsg = this.message.replace(/\s/g,'')
}
}

watch:{
msg(newVal, oldVal){
axios({
method: 'GET',
url: '/url',
params:{ msg:newVal}
}).then(res => {
this.someMsg = res.data.message
})
}
}