多个页面使用到一些名称类的同一个接口,借助vuex实现

1.  准备工作

 npm install vuex --save

  

 main中引用vuex


  import Vuex from 'vuex'   

   import store from './store'  //在src下新建store
  Vue.use(Vuex)
  
  new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
  })

2. 在store/index.js调用接口

import Vue from 'vue'
import {get, post} from '@/assets/js/myrequest'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        commonList: []
    },
    mutations: {
        upCommonList(state, data) {
            state.commonList = data
        }
    },
    actions:{
        async getCommonList(context){
            let res = await get(
                `/api/movie/platform`
            )
            let {data} = res
            context.commit('upCommonList', data)
        }
    }
})

3. 在各个页面中的引用

<template>
    <div class="container">
        <h1>WB</h1>
        <div class="box">
            <div v-for="item in commonList" :key="item">{{item.engName}}</div>
        </div>
    </div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
    data(){
        return {
            
        }
    },
    methods: {
        ...mapActions (['getCommonList'])
        },
    computed: {
        ...mapState(['commonList'])

    },
    mounted(){
        this.getCommonList()
    }
}
</script>
<style scoped>
    .container{
         100%;
        height: 100%;
        overflow-y: scroll;
    }
</style>
 
原文地址:https://www.cnblogs.com/xhrr/p/13853044.html