多個頁面使用到一些名稱類的同一個介面,藉助vuex實現
阿新 • • 發佈:2020-10-21
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{ width: 100%; height: 100%; overflow-y: scroll; } </style>