组件数据

1
2
3
4
5
data() {
return {
name: 'nihao~',
};
},

组件的数据都在 data 这个方法里,它返回一个对象,这个对象里的属性就是这个组件数据。

组件方法

1
2
3
4
5
6
7
methods: {
setName() {
setTimeout(() => {
this.name = '你好啊';
}, 3000);
},
},

组件的方法定义在 methods 里,使用的时候就是 this.setName(),this 表示的是组件实例。

计算属性

computed,也是组件里可以使用的一些数据,和 data 不太一样的是,它里面的数据可以通过一个方法生成,最终返回计算出来的数据。

1
2
3
4
5
computed: {
processStatus() {
return this.name === 'nihao~' ? '初始化...' : '成功设置了数据';
},
},

使用的时候

1
2
3
4
<template>
<h3>{{ name }}</h3>
{{ processStatus }}
</template>

数据监视器

监视组件里数据的变化,当变化时做出反应。

1
2
3
4
5
watch: {
name(newName, oldName) {
console.log(`name发生了变化:${oldName}->${newName}`);
},
}

当 name 发生变化时,控制台会打印出结果。

指令

v-on:绑定事件

1
<button v-on:click="resetName">重置</button>

可以简写为:

1
<button @click="setName">设置</button>

v-for:循环

1
2
3
<div v-for="(post, index) in postList" :key="post.id">
{{ index + 1 }} - {{ post.content }} - <small>{{ post.author }}</small>
</div>

注意使用 v-for 的时候,要绑定一个 key,值是唯一的。

v-if:按条件显示内容

1
<div v-if="visible">隐藏的内容</div>
1
2
3
4
5
6
data() {
return {
name: 'nihao~',
visible: false,
};
},

绑定 class

1
:class="{ active: currentItem === index }"

如果  静态 class 和动态 class 同时存在的话,可以绑定一个数组:

1
:class="['menu-item',{ active: currentItem === index }]"

在 vue 组件里导入样式表文件

style 标签中:

1
@import './styles/app.css';