vuex+axios+mock

利用mock模拟数据,axios获取连接,vuex状态管理

主要目录结构
vuex+axios+mock_第1张图片
main.js

import Vue from 'vue'
import App from './App'
import axios from 'axios'
require('./mock/mock.js')
import store from './store/store'

//导入并使用
import VueRouter from 'vue-router'
Vue.use(VueRouter)
Vue.config.productionTip = false
//1.创建组件
import Home from './components/Home.vue';
import Ewallet from './components/Ewallet.vue';

//2.配置路由  注意,名字一定不能错
const routes = [    //若这里是 xxx,那么第25行应是 routers:xxx
  {
      path: '/home', component: Home },
  {
      path: '/ewallet', component: Ewallet },
  {
      path: '*', redirect: '/ewallet' }//默认跳转路由
]
//3.实例化VueRouter  注意,名字一定不能错
const router = new VueRouter({
     
  routes // (缩写)相当于 routes: routes
})

// axios并没有提供Vue.use()方法,需要绑定到Vue的原型上。这样可以在其他组件中通过this.$axios使用axios发送请求。
Vue.prototype.$ajax=axios;  

new Vue({
     
  el: '#app',
  router,
  store,
  components: {
      App },
  template: ''
})

mock.js。

import Mock from 'mockjs'
export default Mock.mock('/ewallet',{
     
    'items|3': [{
     
        id: '@id',
        image:'@image(350x200)',
        title1:['登录前主页','登录','登录后主页'],
        title2:['查询列表','查询列表无数据','详细信息表格组合'],
      }]
})

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)
const store=new Vuex.Store({
     
    state:{
     
        newsListShow:null
    },
    mutations:{
     
        changeData(state,res){
     
            state.newsListShow=res.list
        }
    },
    actions:{
     
        saveForm(context){
     
            axios.get('/ewallet').then(res=>{
     
                console.log(res)
                context.commit('changeData',{
     list:res.data.items})
            })
        }
    }
})
export default store;

Ewallet.vue

<template>
  <div id="app-content">
    <router-link to="/home">我的home</router-link>  
    <ul>
      <li v-for="item  in this.$store.state.newsListShow" :key="item.id">{
     {
     item.id}}</li>
    </ul>
  </div>
</template>

<script>
import store from '../store/store'

 export default {
     
  name: 'Ewallet',
  created(){
     
     this.$store.dispatch('saveForm');
  }
}
</script>
<style scoped>

</style>

页面展示
vuex+axios+mock_第2张图片

你可能感兴趣的:(vue)