vue中如何加入横线_Vue+TypeScript中如何处理computed

517cb242b004313cf3eaace21d9969f9.png

什么是「computed」

「computed」是Vue中提供的一个计算属性。它被混入到Vue实例中,所有的getter和setter的this上下文自动的绑定为Vue实例。

计算属性的结果会被缓存,除非依赖的响应式property变化才会重新计算。

「computed」的用途

我们可以使用「computed」对已有的属性数据进行加工处理,得到我们的目标数据。

在TypeScript怎么用

「vue-class-component」中分别为props,watch等提供了对应的装饰器,而「computed」却没有对应的装饰器提供。

在官网 https://class-component.vuejs.org/guide/class-component.html#computed-properties 的实例中,「computed」的功能是通过 「get」实现的。

另一种方案

在实际项目中,将组件修改为TypeScript后,使用 get 实现计算属性,浏览器控制台提示data是非响应式的,数据无法显示。

组件js版

鉴于这个问题,使用创建中间变量的方式进行解决。

组件ts版

总结

Vue+TypeScript的道路是曲折而又充满荆棘的,还有内心足够强大。哈哈


个人公众号:Java码农

Vue 3 + TypeScript ,将 token 放在 Vuex store 需要进行一些类型定义的操作。首先需要定义 `state` 的类型和 `mutation` 的类型: ```typescript // auth 模块 interface AuthState { token: string | null; } interface AuthMutations { setToken(state: AuthState, token: string): void; } const state: AuthState = { token: null, }; const mutations: AuthMutations = { setToken(state, token) { state.token = token; }, }; ``` 接着,定义 `action` 的类型和参数类型: ```typescript interface AuthActions { login({ commit }: { commit: Commit }, { username, password }: { username: string, password: string }): Promise<void>; logout({ commit }: { commit: Commit }): void; } const actions: AuthActions = { async login({ commit }, { username, password }) { // 发送登录请求并获取 token const token = 'xxxxx'; commit('setToken', token); }, logout({ commit }) { // 清除 token commit('setToken', null); }, }; ``` 最后,定义 `store` 的类型和模块类型: ```typescript import { createStore } from 'vuex'; interface RootState {} interface Modules { auth: { state: AuthState; mutations: AuthMutations; actions: AuthActions; }; } export default createStore<RootState>({ modules: { auth: { state, mutations, actions, }, }, }); ``` 这样,就可以在组件使用类型安全的方式来访问和操作 token 了。例如,在组件使用 `mapState` 辅助函数来将 token 映射到计算属性: ```typescript import { mapState } from 'vuex'; import { defineComponent } from 'vue'; export default defineComponent({ computed: { ...mapState('auth', ['token']), }, }); ``` 在模板,你可以直接使用 `{{ token }}` 来访问 token。在组件的方法,也可以使用类型安全的方式来调用 `auth` 模块的 action: ```typescript import { mapActions } from 'vuex'; import { defineComponent } from 'vue'; export default defineComponent({ methods: { ...mapActions('auth', ['login']), async handleLogin() { await this.login({ username: 'xxx', password: 'xxx' }); }, }, }); ``` 这样,就可以在 Vue 3 + TypeScript 应用安全地管理和使用 token 了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值