天天看點

Vue -Ts入門 Vuex (二)

接着上文 Vue -Ts入門 (一)

本人也是第一次寫,是以若有所出處,歡迎指正。

準備工作

按照個人項目實際情況

npm i vuex -S
npm i vuex-class -S
           
檔案夾目錄
Vue -Ts入門 Vuex (二)

main.ts

import Vue from "vue";
import Test1 from "./views/Test1.vue";
+ import store from "./store"

Vue.config.productionTip = false;

new Vue({
+   store,
  render: h => h(Test1)
}).$mount("#app");

           

項目啟動

一、state

store/index.ts

import Vue from "vue";
import Vuex, { StoreOptions } from "vuex"; // StoreOptions 接口 參數 泛型 
import { RootState } from "./types";

Vue.use(Vuex);

const store: StoreOptions<RootState> = {
    state: {
        version: '1.0.0', // a simple property
        coder: 'Posden',
    },
};
export default new Vuex.Store<RootState>(store);
           

PS: 定義接口什麼的,編輯器可以點選檢視

Vue -Ts入門 Vuex (二)

store/types.ts

// 注意一下,可選或者必選選項 不然檢測會報錯
export interface RootState { // 定義的接口要跟根store 中 state 一緻,上面截圖可反映,泛型傳遞在state上
  version: string;
  coder: string;
}
           

Test1.vue

<template>
+	 <div>coder:{{ coder }}</div>
+    <div>版本号:{{ version }}</div>	
</template>

<script>
import { State } from "vuex-class";
import { RootState} from "../store/types";
export default class Test1 extends Vue {
+  @State version! :RootState
+  @State coder! :RootState
	// ......
}
</script>
           
Vue -Ts入門 Vuex (二)

已下内容在一個module

profile

示範

二、module - state

module 檔案準備

store/index.ts

import Vue from "vue";
import Vuex, { StoreOptions } from "vuex";
import { RootState } from "./types";
+ import { profile } from "./profile/index";

Vue.use(Vuex);

const store: StoreOptions<RootState> = {
    state: {
        version: '1.0.0', // a simple property
        coder: 'yp',
    },
+    modules: {
+        profile
+    }
};
export default new Vuex.Store<RootState>(store);
           

profile/index.ts

import { Module } from "vuex"; // module 校驗規則
import { ProfileState ,RootState } from "../types"; // 根state 目前profile State 檢測
export const state: ProfileState = {
    user: {firstName:"我的姓氏"},
};
const namespaced: boolean = true;
export const profile: Module<ProfileState, RootState> = {
    namespaced,
    state,
};
           

store/types.ts

// 注意一下,可選或者必選選項 不然檢測會報錯
export interface RootState {
  version: string;
  coder: string;
}
+export interface ProfileState {
+  user?: User;
+  error?: Boolean
+}
+export interface User {
+  firstName?: string;
+  lastName?: string;
+  email?: string;
+  phone?: string;
+}

           

Test1.vue

<template>
+	 <div>姓:{{profile.user.firstName}}</div>
</template>

<script>
import { State } from "vuex-class";
import { ProfileState,RootState} from "../store/types";
export default class Test1 extends Vue {
+  @State("profile") profile!: ProfileState; // 第一個profile 命名空間 第二個是指派的參數(可重寫,template 引用的)
	// 如果一樣 可以簡寫  @State profile!: ProfileState;
	// ......
}
</script>
           
Vue -Ts入門 Vuex (二)
二、moudle - getters

profile/index.ts

import { Module } from "vuex"; // 校驗規則
+ import { getters } from "./getters";
import { ProfileState ,RootState } from "../types";

export const state: ProfileState = {
    user: {firstName:"我的姓氏"},
};
const namespaced: boolean = true;
export const profile: Module<ProfileState, RootState> = {
    namespaced,
    state,
+    getters,
};
           

profile/getters.ts

import { GetterTree } from "vuex"; // 校驗規則
import { ProfileState , RootState } from "../types";

export const getters: GetterTree<ProfileState, RootState> = {
    fullName(state): string {
        const { user } = state;
        const firstName = (user && user.firstName) || '';
        const lastName = (user && user.lastName) || '你的名'; // 沒有初始值 會取到‘你的命’
        return `${firstName} ${lastName}`;
    }
};
           

Test1.vue

再換個寫法,關于命名空間,擷取其中某個屬性

<template>
+	 <div>{{ fullName }}</div>
</template>

<script>
import { State, Getter } from "vuex-class";
import { ProfileState,RootState} from "../store/types";

const namespace = "profile"

export default class Test1 extends Vue {
+    @Getter('fullName', { namespace }) fullName !: string;
	// ......
}
</script>
           
Vue -Ts入門 Vuex (二)
二、moudle - action / mutations

store/types.ts

export interface ProfileState {
+  book?: object;
  user?: User;
  error?: Boolean
}
           

profile/index.ts

import { Module } from "vuex";
import { getters } from "./getters";
+ import { actions } from "./actions";
+ import { mutations } from "./mutations";
import { ProfileState ,RootState } from "../types";

export const state: ProfileState = {
    user: {firstName:"我的姓氏"},
+    book:{}
};
const namespaced: boolean = true;
export const profile: Module<ProfileState, RootState> = {
    namespaced,
    state,
    getters,
+    actions,
+    mutations
};
           

profile./actions.ts

import { ActionTree } from "vuex"; // 校驗規則
import axios from "axios";
import { ProfileState, RootState } from "../types";

export const actions: ActionTree<ProfileState, RootState> = {
    fetchData({ commit }): any {
        axios({
            url: 'https://www.xxxx.com/api/book/bookList/findBybookCate?Pcid=5d74bc4b8e42ee0f2887c36e&cid=5d3d0506e1d8c632cc000862&pagesize=8&page=1'
        }).then((response) => {
            const payload: any = response && response.data && response.data.item;
            commit('profileLoaded', payload);
        });
    }
};

           

profile/mutations.ts

import { MutationTree } from "vuex";
import { ProfileState } from "../types";

export const mutations: MutationTree<ProfileState> = {
    profileLoaded(state, payload) {
        state.error = false;
        state.book = payload;
    },
};

           

Test1.ts

<template>
...
    <ul>
      <li v-for="(item,index) in book" :key="index">
        <img :src="item.bookImg" alt="">
        <div>{{ item.bookName}}</div>
        <div>{{ item.bookAuthor}}</div>
        <div>¥{{ item.bookPrice}}</div>
      </li>
    </ul>
...
</template>
<script>
import { State, Action, Getter } from "vuex-class";

  @State('book', { namespace }) book !: object;
  @Action('fetchData', { namespace }) fetchData: any


  mounted() {
    this.fetchData()
  }
</script>
           
Vue -Ts入門 Vuex (二)

當然你也可以不在

store/index

注冊module,異步按需加載

public beforeCreate(){
    this.$store.registerModule('profile',profile)
  }
  public beforeDestroy() {
    this.$store.unregisterModule('profile')
  }
           

至此,一個vuex-ts 入門完工。如果對你覺得不錯、點個贊呗。