使用VueCli3+TypeScript+Vuex一步步构建todoList的方法(3)

<template> <div> <todoList :todoList="todoList" @add-item="addTodoList" @removeItem="addTodoLisItem" /> </div> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; import todoList from '@/components/todoList.vue'; // @ is an alias to /src import { State, Getter, Action } from 'vuex-class'; @Component({ components: { todoList } }) export default class Home extends Vue { @State(state => state.todolist.todoList) private todoList!: string[]; @Action('todolist/addList') private addList!: (val: string) => void; @Action('todolist/removeItem') private removeItem!: (index: number) => void; public addTodoList(val: string) { console.log(val); this.addList(val); } private created() { console.log('i add life cycle funciton -- created'); } private addTodoLisItem(index: number) { this.removeItem(index); } } </script>

有关 vuex-class 的调用有以下几点注意

@State 如果有分模块,必须使用 state => state.xxx.xxx 的形式获取state

@Action 中函数的声明,形参必须和方法保持一致

所有的代码到此为止,使用 npm run serve 即可查看应用,保留原有 routes 文件,保持应用的健壮性。

写在最后

本文只是介绍了一个简单构建 ts-vue 应用的例子,对于框架的健壮和可扩展性有需要慢慢考虑,比如 webpack 的配置,适应测试,生产等各种环境的区分,axois 的封装,等等。

对于vue + ts 的配方,文章还有很多 vue 的特性没有去兼容,比如 this.refs 的使用,比如 vue-property-decorator 其他特性的使用。

由于官方文档对 ts 的介绍有限,所以以上代码肯定有不足的地方,希望大家指正。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/cb5a84cc4cf3d177a0045a2cc937512e.html