對于我的個人專案,我對 Vuex 感到好奇,更具體地說,我對不同屬性如何協同作業感到好奇。如果這是一個重復的問題,我提前道歉。
我正在使用 Vue3,這是我配置商店的方式:
// store/index.js
import { createStore } from "vuex";
import axios from "axios";
let connected = false;
axios.defaults.withCredentials = true;
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
export default createStore({
state: {
connected,
},
getters: {
getConnected: (state) => {
return state.connected;
},
},
mutations: {
setConnected(state, isConnected) {
console.log("in mutations");
return (state.connected = isConnected);
},
},
actions: {
isConnected: ({ commit }) => {
axios
.get("/auth/me")
.then(() => {
console.log("here positive");
commit("setConnected", true);
})
.catch(() => {
console.log("here negative");
commit("setConnected", false);
});
},
},
modules: {},
});
這state是我們存盤的內容,mutations是對狀態actions的操作,是對mutationsvia的操作commits。
這是我的 Vue 頁面:
<template>
<v-row justify="start">
<nav>
<router-link to="/">Home</router-link> |
<router-link :to="connected ? '/me' : '/signup'">{{
connected ? "Profile Page" : "Sign up"
}}</router-link>
|
<router-link :to="connected ? '/logout' : '/login'">{{
connected ? "Logout" : "Login"
}}</router-link>
</nav>
</v-row>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
name: "NavBar",
data() {
return {
connected: false,
};
},
methods: {
...mapGetters(["getConnected"]),
...mapActions(["isConnected"]),
},
mounted() {
this.connected = this.getConnected();
console.log("connected", this.connected);
},
};
</script>
<style>
nav {
padding: 30px;
}
nav a {
font-weight: bold;
color: #2c3e50;
}
nav a.router-link-exact-active {
color: #42b983;
}
</style>
我的問題,我如何觸發actions?我是否需要通過顯式呼叫該方法mapActions或者我錯過了什么?
蒂亞!
uj5u.com熱心網友回復:
您可以像任何其他方法一樣呼叫它:
async mounted() {
await this.isConnected()
this.connected = this.getConnected();
console.log("connected", this.connected);
},
更多的here
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510581.html
