Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility to map typed state #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/components/HelloWorld.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h1>{{ backwardsMessage }}</h1>
<p>
For a guide and recipes on how to configure / customize this project,<br />
check out the
Expand Down Expand Up @@ -127,12 +127,18 @@
</template>

<script lang="ts">
import { mapRootState } from "@/store";
import Vue from "vue";

export default Vue.extend({
name: "HelloWorld",
props: {
msg: String,
computed: {
...mapRootState(["message"]),
backwardsMessage(): string {
const chars = this.message.split("");
chars.reverse();
return chars.join("");
},
},
});
</script>
Expand Down
15 changes: 14 additions & 1 deletion src/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
import Vue from "vue";
import Vuex from "vuex";
import { mapTypedState } from "./util";

Vue.use(Vuex);

export interface RootState {
message: string;
}

const state: RootState = {
message: "olleH",
};

export function mapRootState(keys: (keyof RootState)[]) {
return mapTypedState<RootState>(keys);
}

export default new Vuex.Store({
state: {},
state,
mutations: {},
actions: {},
modules: {},
Expand Down
8 changes: 8 additions & 0 deletions src/store/util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { mapState } from "vuex";

export function mapTypedState<State>(keys: (string & keyof State)[]) {
type Key = typeof keys[number];
return mapState(keys) as {
[key in Key]: () => State[key];
};
}
2 changes: 1 addition & 1 deletion src/views/Home.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js + TypeScript App" />
<HelloWorld />
</div>
</template>

Expand Down