关于vue3与TS类疑问

关于vue3与TS类疑问

实现一个简单的tab切换

<ul class="listWra">

<li v-for="(item, index) in topList" :class="['top_btn', { active: item.index === act }]"

@click="devUnit(item.index)" :key="item.id">

<button type="button">{{ item.name }}</button>

</li>

</ul>

<script lang="ts">

import {defineComponent, reactive, ref} from "vue";

export default defineComponent({

setup() {

const topList = reactive([

{name: 'TAB1', id: 0, index: 0},

{name: 'TAB2', id: 1, index: 1},

{name: 'TAB3', id: 2, index: 2},

])

const act = ref(0)

const devUnit = (index: number) => {

act.value = index

}

}

})

</script>

<style>

.active{

color: red

}

</style>

然后我想把页面逻辑都提取到一个外部类里

outer.ts

interface ITopList {

[_:string]: string | number

}

export class Logic {

public topList: ITopList[]

public act: number

constructor() {

this.topList = [

{name: 'TAB1', id: 0, index: 0},

{name: 'TAB2', id: 1, index: 1},

{name: 'TAB3', id: 2, index: 2},

]

this.act = 0

}

devUnit = (index: number) => {

this.act = index

}

}

HTML

<ul class="listWra">

<li v-for="(item, index) in topList" :class="['top_btn', { active: item.index === act }]"

@click="devUnit(item.index)" :key="item.id">

<button type="button">{{ item.name }}</button>

</li>

</ul>

script

<script lang="ts">

import {defineComponent, reactive} from "vue";

import {Logic} from ./outer.ts

export default defineComponent({

setup() {

const data = reactive(new Logic())

return {

...toRefs(data)

}

}

})

</script>

这样写后,值都能取到,方法触发的是类里的方法,类里面的act值改变了,但没有在视图上更新,也就不能响应式的更新视图,请问该怎么改


回答:

自己解决了。。

创建类的时候引入vue的reactive让类成员变成proxy对象就能实现响应式了

outer.ts

import {reactive} from 'vue'

interface ITopList {

[_:string]: string | number

}

export class Logic {

// public topList: ITopList[]

// public act: number

public pageData = reactive({

topList: ITopList[],

act: number

})

constructor() {

this.pageData.topList = [

{name: 'TAB1', id: 0, index: 0},

{name: 'TAB2', id: 1, index: 1},

{name: 'TAB3', id: 2, index: 2},

]

this.pageData.act = 0

}

devUnit = (index: number) => {

this.pageData.act = index

}

}

页面上取用使用对象取出来

const active = item.index === pageData.act

以上是 关于vue3与TS类疑问 的全部内容, 来源链接: utcz.com/p/937594.html

回到顶部