WEB前端:vuejs全家桶(40):项目开发:脚手架+vuex+


## 一、 准备工作

###1. 初始化项目
    vue init webpack itany
    cd itany
    cnpm install
    cnpm install less less-loader -D
    cnpm install vuex axios -D
    npm run dev

### 2. 项目资源
    |-reset.css
    |-data.json

### 3. 创建目录结构
    首先清除项目中的部分内容

    创建如下目录结构:
        |-data.json
        |-static
            |-css
                |-reset.css

### 4. 配置API接口,模拟后台数据
    使用express框架启动一个Node服务器,配置API接口,模拟后台数据
    参考
    https://blog.csdn.net/qq_34645412/article/details/78833860
    
    在webpack.dev.conf.js添加配置
```clike
const express = require('express')
const app = express() //请求server
var appData = require('../data.json') //加载本地数据文件
var seller = appData.seller //获取对应的本地数据
var goods = appData.goods
var ratings = appData.ratings
var apiRoutes = express.Router()
app.use('/api', apiRoutes) //通过路由请求数据

在这里插入图片描述

 before(app) {
            app.get('/api/seller', (req, res) => {
                    res.json({
                            errno: 0,
                            data: seller
                        }) //接口返回json数据,上面配置的数据seller就赋值给data请求后调用
                }),
                app.get('/api/goods', (req, res) => {
                    res.json({
                        errno: 0,
                        data: goods
                    })
                }),
                app.get('/api/ratings', (req, res) => {
                    res.json({
                        errno: 0,
                        data: ratings
                    })
                })

        }

在这里插入图片描述
测试API:
http://localhost:8080/api/seller
http://localhost:8080/api/goods
http://localhost:8080/api/ratings
在这里插入图片描述


二、项目整体结构开发

1步:在src下新建store目录,在store目录下新建modules目录,再新建文件

在这里插入图片描述

2步:在modules目录下的sellers.js、goods.js、ratings.js定义属性
import types from '../types.js'

const state = {

}

const getters = {

}

const actions = {

}

const mutations = {

}

export default {
    state,
    getters,
    actions,
    mutations
}
3步:在src下的index.js引入并导出其他模板
import Vue from 'vue'
import Vuex from 'vuex'
// 导入js模块
import getters from './getters'
import actions from 'actions'
import seller from './modules/seller'
import goods from './modules/goods'
import ratings from './modules/ratings'

Vue.use(Vuex);

// 导出
export default new Vuex.Store({
    getters,
    actions,
    modules: {
        seller,
        goods,
        ratings
    }
})
4步:在main.js引入. / store / index.js模块,并new一个实例
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
// 引入. / store / index.js模块
import store from './store/index.js'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})
5步:在seller.js写请求动作
import axios from 'axios'

 // 发送请求
const actions = {
    getSeller({ commit, state }) {
        axios.get('/api/seller').then(resp => {
            console.log(resp);
        })
    }
}

6步:Header.vue发出请求
<template>
    <div class="header">
        header
    </div>
</template>
<script>
export default {
    created() {
        this.$store.dispatch('getSeller');
    },
}
</script>

<style lang="less" scope>
    .header{
        height: 34px;
        background-color: rgba(7,17,27,0.1);
        font-size: 14px;
    }
</style>
7步:在seller.js接收数据
import types from '../types.js'
import axios from 'axios'

// 定义属性(数据)
const state = {
        seller: {}
    }
    // getters 用来获取属性
const getters = {
        seller(state) {
            return state.seller;
        }
    }
    // 定义 actions ,要执行的动作,如流程的判断、异步请求
const actions = {
    // ({commit,state}) 这种写法是 es6 中的对象解构
    getSeller({ commit, state }) {
        axios.get('/api/seller').then(resp => {
            // console.log(resp);
            //提交一个名为 types.GET_SELLER的变化,名字可自定义,可以认为是类型名,
            // 与下方 mutations 中的 types.GET_SELLER 对应
            //commit 提交变化,修改数据的唯一方式就是显式的提交 mutations
            if (resp.data.errno == 0) { //获取数据
                commit(types.GET_SELLER, resp.data.data);
            }
        });
    },
}

// 定义 mutations ,处理状态(数据) 的改变
const mutations = {
        //与上方 commit 中的 'types.GET_SELLER' 相对应
        [types.GET_SELLER](state, data) {
            state.seller = data;
        }
    }
    // 导出 对象
export default {
    state,
    getters,
    actions,
    mutations
}
8步:在Header.vue获取数据


参考
https://www.cnblogs.com/yaowen/p/8927343.html
<template>
    <div class="header">
    //第3步:显示数据
        {{seller.name}}
    </div>
</template>
<script>
//第1步:引入mapGetters函数
import {mapGetters} from 'vuex'
export default {
    created() {
        this.$store.dispatch('getSeller');
    },
    //第2步:通过mapGetters获取数据
    computed:mapGetters([
        'seller'
    ])
}
</script>

<style lang="less" scope>
    .header{
        height: 34px;
        background-color: rgba(7,17,27,0.1);
        font-size: 14px;
    }
</style>
9步:mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用

参考
https://vuex.vuejs.org/zh/guide/state.html#%E5%AF%B9%E8%B1%A1%E5%B1%95%E5%BC%80%E8%BF%90%E7%AE%97%E7%AC%A6
<template>
    <div class="header">
        {{seller.name}}
        <img :src="seller.avatar">
        <br>
        //第3步:显示效果
        {{msg}}
    </div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
    created() {
        this.$store.dispatch('getSeller');
    },
    computed:{
        //第1步:加在mapGetters前面加...不能加多或者加少
        ...mapGetters([
        'seller'
    ]),
     //第2步:使用局部计算属性
    msg(){
        return "welcome to vuejs!";
    }
    }
    
}
</script>

<style lang="less" scope>
    .header{
        height: 134px;
        background-color: rgba(7,17,27,0.1);
        font-size: 14px;
        img{
        width: 64px;
        height: 64px;
        border-radius: 2px;
    }
    }
    
</style>
10步:在src的components的detail新建Detail.vue
 <template>
    <div class="detail" v-show="showDetail">
        详情页
    </div>
</template>

<script>
export default {
    
}
</script>
<style lang="less" scoped>
    .detail{
        position: fixed;
        top: 0;
        left: 0;
        z-index: 666;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(7,17,27,0.8);

    }
</style>
11步:在seller.js添加VUEX
import types from '../types.js'
import axios from 'axios'

// 定义属性(数据)
const state = {
        seller: {},
        detailShow: false

    }
    // getters 用来获取属性
const getters = {
        seller(state) {
            return state.seller;
        },
        detailShow(state) {
            return state.detailShow;
        }
    }
    // 定义 actions ,要执行的动作,如流程的判断、异步请求
const actions = {
    // ({commit,state}) 这种写法是 es6 中的对象解构
    getSeller({ commit, state }) {
        axios.get('/api/seller').then(resp => {
            // console.log(resp);
            //提交一个名为 types.GET_SELLER的变化,名字可自定义,可以认为是类型名,
            // 与下方 mutations 中的 types.GET_SELLER 对应
            //commit 提交变化,修改数据的唯一方式就是显式的提交 mutations
            if (resp.data.errno == 0) { //获取数据
                commit(types.GET_SELLER, resp.data.data);
            }
        });
    },
    

}

// 定义 mutations ,处理状态(数据) 的改变
const mutations = {
        //与上方 commit 中的 'types.GET_SELLER' 相对应
        [types.GET_SELLER](state, data) {
            state.seller = data;
        }
    }
    // 导出 对象
export default {
    state,
    getters,
    actions,
    mutations
}
12步:在types.js添加
const GET_SELLER = "GET_SELLER"
const SHOW_DETAIL = "SHOW_DETAIL"
const HIDE_DETAIL = "HIDE_DETAIL"


export default {
    GET_SELLER,
    SHOW_DETAIL,
    HIDE_DETAIL,
   
}
13步:在seller.js添加VUEX
在这里插入代码片
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值