文章目录
p23 VueRouter路由的使用(下)
router-link的v-slot
router-view的v-slot
动态添加路由
路由导航守卫
Vuex的状态管理
p24
mapState
如何在setup中使用mapState
<template>
<h2>{
{ sCounter }}</h2>
<p>{
{ counter }}</p>
<p>{
{ name }}</p>
<p>{
{ age }}</p>
<p>{
{ weight }}</p>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</template>
<script>
import {
mapState, useStore } from "vuex";
import {
computed } from "vue";
export default {
setup() {
const store = useStore();
const sCounter = computed(() => store.state.counter);
const storeStateFns = mapState(["counter", "name", "age", "weight"]);
const storeState = {
};
Object.keys(storeStateFns).forEach((fnKey) => {
const fn = storeStateFns[fnKey].bind({
$store: store });
storeState[fnKey] = computed(fn);
});
return {
sCounter,
...storeState,
};
},
};
</script>
封装
useState.js
import {
computed } from 'vue'
import {
mapState, useStore } from 'vuex'
export function useState(mapper) {
// 拿到store
const store = useStore()
// 获取到对应的对象的functions: {name: function, age: funciton}
const storeStateFns = mapState(mapper)
// 对数据进行转换
const storeState = {
}
Object.keys(storeStateFns).forEach((fnKey) => {
const fn = storeStateFns[fnKey].bind({
$store: store });
storeState[fnKey] = computed(fn);
});
return storeState
}
App.vue
<template>
<p>{
{ counter }}</p>
<p>{
{ name }}</p>
<p>{
{ age }}</p>
</template>
<script>
import {
useState } from "./hooks/useState";
export default {
setup() {
const storeState = useState(["counter", "name", "age"]);
return {
...storeState,
};
},
};
</script>
getters
mapGetters
封装
Mutation