1. 程式人生 > 實用技巧 >Vue+typescript+vuex專案實踐學習筆記

Vue+typescript+vuex專案實踐學習筆記

vue+ts+vuex+vue-router專案實踐筆記:

  使用vue cli3.0腳手架建立包含 typescript 的vue專案,然後需要安裝下面這兩個依賴檔案:

  npm install  vue-template-compiler
   
   npm install vuex-class

ts與js專案的區別在於:變數需要指定型別,方法需要指定返回型別,狀態管理庫store裡面的寫法不一樣,元件裡面的裝飾器不同以及觸發state狀態改變的方式不同:

1. 變數需要指定型別:(以login.vue元件為例)

 // vue下面的data屬性
  public form: InterForm = {
    password:
"", username:"", } ; public showPassword: boolean = false;

2. 方法需要指定返回型別:(以login.vue元件為例)

  

//mounted
  public mounted(): void {
    
  };

3.狀態管理庫store裡面的寫法不同:

  

  1》需要在store資料夾裡面定義一個檔案:mutation-types.ts,內容如下:

// login頁面
export const LOGIN_FORM = "LOGIN_FORM";
export const LOGIN_SHOW_PASSWORD 
= "LOGIN_SHOW_PASSWORD"; // export const LOGIN_RULES = "LOGIN_RULES"; // user頁面 export const USER_TIMER = "USER_TIMER"; export const USER_AREAS_LABEL = "USER_AREAS_LABEL"; export const USER_REGION_OPTIONS = "USER_REGION_OPTIONS"; export const USER_SECTION_OPTIONS = "USER_SECTION_OPTIONS"; export const USER_AREAS_IDS
= "USER_AREAS_IDS"; export const USER_AREAS_ID = "USER_AREAS_ID"; export const USER_SEARCH_PARAMS = "USER_SEARCH_PARAMS"; export const USER_FORMRULES = "USER_FORMRULES"; export const USER_LOADING = "USER_LOADING"; export const USER_PAGINATION = "USER_PAGINATION"; export const USER_TABLE_DATA = "USER_TABLE_DATA"; export const USER_USER_DATA = "USER_USER_DATA"; export const USER_USER_DATA_COPY = "USER_USER_DATA_COPY"; export const USER_MODAL_EDIT = "USER_MODAL_EDIT"; export const USER_TABLECOLUMNS = "USER_TABLECOLUMNS";

2》在store資料夾裡面新建一個資料夾modules用於存放專案中各個模組的state狀態儲存檔案,然後再modules模組裡面建立一個login.ts檔案,用於儲存登入頁面的狀態,程式碼如下:

import {
  LOGIN_FORM,
  LOGIN_SHOW_PASSWORD,
} from "../mutation-types";

import { Commit } from "vuex";

/** 格式 約束 */
export interface InterForm {  // form表單介面
  password: string;
  username: string;
}
export interface InterState {  // store 介面
  form: InterForm;
  showPassword: boolean;
}
const state: InterState = {
  showPassword: false,  
  form: {  // 分頁
    password:"",
    username: ""
  }
};
// getters
const getters = {
  [LOGIN_FORM]: (orgState: InterState) => orgState.form,
  [LOGIN_SHOW_PASSWORD]: (orgState: InterState) => orgState.showPassword,
};
// mutations
const mutations = {
  [LOGIN_FORM](orgState: InterState, value: InterForm): void {
    orgState.form = value;
  },
  [LOGIN_SHOW_PASSWORD](orgState: InterState, value: boolean): void {
    orgState.showPassword = value;
  },
};
// actions
const actions = {
  [LOGIN_FORM](context: { commit: Commit, state: InterState }, value: string): void {
    context.commit(LOGIN_FORM, value);
  },
  [LOGIN_SHOW_PASSWORD](context: { commit: Commit, state: InterState }, value: number): void {
    context.commit(LOGIN_SHOW_PASSWORD, value);
  },
};
const Index = {
  state,
  getters,
  mutations,
  actions,
};
export default Index;

4. 元件裡面的裝飾器不同以及觸發state狀態改變的方式不同:以login.vue元件為例:

<script lang='ts'>
  import { loginApi } from '@/service/index.ts';
  import { Vue, Component, Watch } from "vue-property-decorator";
  import { Getter, Action } from "vuex-class";
  import {
  LOGIN_FORM,
  LOGIN_SHOW_PASSWORD,
  GLOBAL_USERINFO,
  } from "@/store/mutation-types";
  import { InterForm } from '@/store/modules/login';
  import { InterUserInfo } from '@/store/state';

  @Component
  export default class Login extends Vue {
    // data
    public form: InterForm = {
      password:"",
      username:"",
    } ; 
    public showPassword: boolean = false;  

    // action
    @Action(LOGIN_FORM) public formAct: (val: InterForm) => void;
    @Action(LOGIN_SHOW_PASSWORD) public showPasswordAct: (val: boolean) => void;
    @Action(GLOBAL_USERINFO) public userInfoAct: (val: InterUserInfo) => void;

  //mounted
    public mounted(): void {
      
    };
    
  //methods

  //登入校驗
  public validLogin():void {
    this.$refs.form.validate((valid:boolean) => {
      if (valid) {
        this.submitLogin()
      }
    });
  };
  public submitLogin():void {
      // 調介面
      loginApi.login({
        username: this.form.username,
        password: this.form.password,
      }).then((res) => {
        this.userInfoAct(res.data.data);
        localStorage.setItem('id', res.data.data.id);
        localStorage.setItem('user_info', res.data.data);
        this.$message({
          message: '登入成功',
          type: 'success'
       });
       this.$router.push({path:'/user/user-mgr'})
      });
  }
}
</script>

5. 補充說明:

變數前面的修飾符(public)預設可以不用寫

TypeScript 可以使用三種訪問修飾符(Access Modifiers),分別是 public、private 和 protected。

  • public 修飾的屬性或方法是公有的,可以在任何地方被訪問到,預設所有的屬性和方法都是 public 的
  • private 修飾的屬性或方法是私有的,不能在宣告它的類的外部訪問
  • protected 修飾的屬性或方法是受保護的,它和 private 類似,區別是它在子類中也是允許被訪問的

vue-property-decorator 裡面有很多裝飾器,它完全依賴於:vue-class-component,當使用vue要使用ts的時候,需要用到這些裝飾器;

具體用法可以參照:https://www.npmjs.com/package/vue-property-decorator 或者參照:https://www.cnblogs.com/cczlovexw/p/11444984.html

vuex-class 的作用主要是為了在ts模式下使用vuex狀態管理庫的getters/actions/mutations

以上便是我的專案實踐筆記總結,有不對之處可留言指出,謝謝。