Vue.js 将按钮参数传递给 Vuex 商店

Vue.js Passing Button Parameters to Veux Store

虽然我能够使用 Vuex Mapstate 获取数据,并将我的搜索字段中的值传递到 Vuex,但我目前面临的问题是当我尝试将参数从按钮传递到 Vuex 时为了 Post 数据到后端 API 应用程序,虽然 POST axois 函数在 vue.js 页面的方法部分有效,但我想将其移动到我的 Store index.js 这样不同页面上的其他元素就可以调用它作为 Store 函数。

Vue 页面

<template>
  <div class="container" style=" padding-top: 50px;">
     <!-- Bootswatch -->
 
    <div class="row my-5 card-wrapper">
      
      <div
            class="col-lg-4 col-md-6 mb-4"
            v-for="(vdesk, index) in vdesks"
            :key="index">

        <div class="card h-200">
            <div class="embed-responsive embed-responsive-16by9">
                <!-- Display Image -->
                <template v-if="vdesk.MachineOpt == 'Windows'">
                    <div class="text-center">
                        <img v-bind:src="require('@/assets/windows.png')" />
                    </div>
                </template>
                <template v-if="vdesk.MachineOpt == 'Ubuntu'">
                    <div class="text-center">
                        <img v-bind:src="require('@/assets/linux.png')" />
                    </div>
                </template>

          <div class="card-body">
                <!-- Display vDesk Machine Name -->
                <h4 class="card-title">
                    vDesk: {{ vdesk.MachineName }}
                </h4>
              <!-- Display vDesk Status -->
              <p class="card-text">Machine State: {{ vdesk.MachineStatus }}</p>

              <!-- Action Buttons -->
              <template v-if="vdesk.MachineStatus != 'Powered Off' && vdesk.MachineStatus != 'Running Job'">
                <button type="button" 
                        :v-model="TitleDesk"
                        class="btn btn-outline-warning"
                        :value="({'vSphere':'Horizon','PowerCycle':'PowerOff', 'vDesk':vdesk})"
                        @click="SubmitPowerCycle({'vSphere':'Horizon','PowerCycle':'PowerOff', 'vDesk':vdesk})">
                        <i class="fas fa-power-off"></i></button>

                 <button type="button" 
                         class="btn btn-outline-primary" 
                         @click="SubmitPowerCycle({'vSphere':'Horizon','PowerCycle':'Restart', 'vDesk':vdesk})">
                         <i class="fas fa-recycle"></i></button>

                 <button type="button" 
                         class="btn btn-outline-danger"
                         @click="SubmitPowerCycle({'vSphere':'Horizon','PowerCycle':'Delete', 'vDesk':vdesk})">
                         <i class="fas fa-trash"></i></button>
  
              <template v-if="vdesk.MachineOpt == 'Windows'">
                   <button type="button"
                           class="btn btn-outline-info">
                           <i class="fas fa-desktop"></i></button>
              </template>
              </template>

              <template v-if="vdesk.MachineStatus == 'Powered Off'">
                <button type="button" 
                         class="btn btn-outline-danger"
                         @click="SubmitPowerCycle({'vSphere':'Horizon','PowerCycle':'Delete', 'vDesk':vdesk})">
                         <i class="fas fa-power-off"></i></button>
      
                <button type="button" 
                         class="btn btn-outline-danger"
                         @click="SubmitPowerCycle({'vSphere':'Horizon','PowerCycle':'Delete', 'vDesk':vdesk})">
                         <i class="fas fa-trash"></i></button>
              </template>

              <template v-if="vdesk.MachineStatus == 'Running Job'">
                <Spinner />
              </template>
              
                <!-- Footer -->
               <div class="card-footer" style="margin-top: 5px;">
                 <small small-class="text-muted" >
                   Desktop Pool: {{ vdesk.vPool }}
                 </small>
                 <br>
                   <small small-class="text-muted" >
                   Horizon Server: {{ vdesk.vCenter }}
                 </small>
               </div>
              </div>
        </div>
      </div>
          <!-- End of Card --> 
    </div>
    </div>
  </div>
</template>

<script>

//TO-DO Move SubmitPowerCycle to VUEX 
import Spinner from '@/components/Spinner.vue';
import {mapState} from 'vuex';

export default {
props: {

},

data() {
    return {
      polling: null,  
    };
    },

message: '',



computed:{
  ...mapState(['vdesks']),

TitleDesk:{
  get() {
      return this.$store.getters.TitleDesk;
  },
  set(TitleDesk) {
    this.$store.commit('Click', TitleDesk)
  }
}
},

components: {
    Spinner
},


methods: {
   SubmitPowerCycle(){
     this.$store.dispatch('PowerCycle', this.payload);
   },


  pollData () {
    this.polling = setInterval (() => {
      this.$store.dispatch("FeatchvDesks")
    }, 12000)
  }
},

beforeUnmount() {
  clearInterval(this.polling)
},

created() {
    this.$store.dispatch("FeatchvDesks")
    this.pollData()
  },
};
</script>

Vuex

    import { createStore } from "vuex";
import axios from "axios"


export default createStore({
  state: {
    vdesks: [],
    SearchvDesks: [],
    PostTitle: '',
    Click: []
  },
  
  getter: {
    TitleUser: state => {
      return state.PostTitle;
    },
    vdesk: state => {
      return state.PostTitlevDesk;
    },
    TitleDesk: state => {
      return state.Click;
    }
  },
  
  mutations: {
  SET_VDESKS(state, payload){
    state.vdesks = payload;
  },

  SET_USERVDESKS(state, payload){
    state.SearchvDesks = payload;
},

  PostTitle(state, payload) {
    state.PostTitle = payload;
 },
 Click(state ,payload) {
    state.Click = payload
 }
},

  actions: {
    FeatchvDesks({commit}){
      const path = 'http://localhost:5000/horizon';
      axios.get(path)
      .then((res) => {
          (commit("SET_VDESKS", res.data.vdesks))
      })
      .catch((error) => {
          console.error(error)
      });
  },

  FetchUservDesks({commit, state}) {
    const path = 'http://localhost:5000/searchdata';
    axios.post(path, {
      TitleUser: state.PostTitle
  })
    .then((res) => {
        (commit("SET_USERVDESKS", res.data.SearchvDesks))  
    })
    .catch((error) => {
        console.error(error);
    });
  },

  SubmitPowerCycle({commit,state}){
    const path = 'http://localhost:5000/horizon';
    axios.post(path,state.Click)
    .then((res) =>{ 
      (commit("Click", res.data.SearchvDesks))  
    })
    .cath((error)=>{
      console.error(error);
    });
  }

},
  modules: {},
});

如果我的理解正确,你想要一个可以被你的任何 vue.js 组件使用的 POST api 调用。

最好使用 Vuex 操作,然后使用 mapActions

映射该操作

在你的 vuex 文件中:

...
actions: {
  async postData({state}, data) {
    const result = await axios.post('//your/endpoint', data);
    return result
  }
}

在你的 vue 组件中:

<template>
  <div>
    <button @click="postData('data to post')">Post</button>
  </div>
</template>

<script>
  import { mapActions } from 'vuex'
  export default {
    methods: {
      ...mapActions(['postData'])
    }
  }
  
  </script>