vue3+ts怎么做点击关注
时间: 2023-12-21 11:04:43 浏览: 25
首先,在 Vue3 中使用 TypeScript,需要安装 `@vue/cli` 的 TypeScript 插件。可以通过以下命令安装:
```
npm install -g @vue/cli
vue create my-app
cd my-app
vue add typescript
```
安装完成后,可以创建一个 `FollowButton` 组件,在该组件中定义一个 `follow` 方法,用于处理点击关注的逻辑。可以在组件中使用 `v-on:click` 指令来绑定点击事件,并在 `follow` 方法中处理关注逻辑。例如:
```html
<template>
<button v-on:click="follow">{{ buttonText }}</button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'FollowButton',
props: {
userId: {
type: Number,
required: true
},
isFollowed: {
type: Boolean,
default: false
}
},
data() {
return {
buttonText: this.isFollowed ? '取消关注' : '关注'
};
},
methods: {
follow() {
if (this.isFollowed) {
// 取消关注
// ...
this.buttonText = '关注';
} else {
// 关注
// ...
this.buttonText = '取消关注';
}
this.isFollowed = !this.isFollowed;
}
}
});
</script>
```
在父组件中使用 `FollowButton` 组件,并传递 `userId` 和 `isFollowed` props。例如:
```html
<template>
<div>
<follow-button :user-id="userId" :is-followed="isFollowed"></follow-button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import FollowButton from './FollowButton.vue';
export default defineComponent({
name: 'User',
components: {
FollowButton
},
data() {
return {
userId: 123,
isFollowed: false
};
}
});
</script>
```
这样就可以在 Vue3 + TypeScript 中实现点击关注的功能。