1、普通ts方式
习惯了Vue2的朋友们,应该更加喜欢这种方式。学习成本就是增加一个ts,其他与Vue2没有什么差距。
<script lang="ts">
export default {
data() {
return {
activeIndex: 'home',
list: [
{
key: 'home',
name: '首页',
},
{
key: 'case',
name: '案例',
},
{
key: 'experience',
name: '经历',
},
{
key: 'about',
name: '关于',
},
],
}
},
methods: {
handleSelect(key:string, keyPath:string[]) {
this.activeIndex=key;
this.$router.push({
name: key
})
}
}
}
</script>
2、ts setup语法糖模式
这种模式下,更加适合新手去使用。相对之下对于react开发者来说,更加友好一些。
<script lang="ts" setup>
import router from '@/router';
import { ref } from 'vue'
// 导航名称
const list: { key: string, name: string }[] = [
{
key: 'home',
name: '首页',
},
{
key: 'case',
name: '案例',
},
{
key: 'experience',
name: '经历',
},
{
key: 'about',
name: '关于',
},
]
const activeIndex = ref('home')
const handleSelect = (key: string, keyPath: string[]) => {
router.push({
name:key
})
}
</script>