美文网首页
09_02.vuex的使用

09_02.vuex的使用

作者: Robyn_Luo | 来源:发表于2017-11-23 15:16 被阅读0次
    1. 下载vuex

    npm i vuex -S

    2. 导入并启用
    • 在src/js/main.js中
      • import Vuex from vuex
      • Vue.use(vuex)
    3. 配置共享状态
    • 多增加一个store的配置项,值为Vuex.Store的实例
    4. 测试全局状态
    • 在创建store实例的时候,添加一个state配置项
    • 该配置项与组件的data是一样的,赋值一个对象,添加一些共享数据
    • 添加数据可以在任意组件中,通过$store.state.名称来访问状态值
    5. 测试修改状态
    • vuex专门为修改状态提供了新的配置项mutations,他类似于咱们之前的methods,用来定义一些方法
    • 但是这里面的方法第一个参数为自动传入的state,第二个为可选的参数,是用户根据自己需要传入的参数
    • 方法内部得到state与参数,依据方法作用去修改对应的状态值,那么使用了该全局状态的组件视图就会自动更新
    5. demo
    5. 代码:
    • 分析:

      • 首先在main.js里面引入以及使用



      • 底部要跟着变化,所以去底部模块修改相关数据


      • 在购物车模块里面点击事件


    • 完整代码块:

    • src/component/common/footer.vue

    <template>
      <footer>
        <nav class="mui-bar mui-bar-tab">
          <router-link class="mui-tab-item" to="/index">
            <span class="mui-icon mui-icon-home"></span>
            <span class="mui-tab-label">首页</span>
          </router-link>
          <router-link class="mui-tab-item" v-bind:to="{ name: 'gl' }">
            <span class="mui-icon mui-icon-extra mui-icon-extra-gift"></span>
            <span class="mui-tab-label">商品购买</span>
          </router-link>
          <router-link class="mui-tab-item" v-bind:to="{ name: 'sc' }">
            <span class="mui-icon mui-icon-extra mui-icon-extra-cart">
              <span class="mui-badge">{{ $store.state.buyTotal }}</span>
            </span>
            <span class="mui-tab-label">购物车</span>
          </router-link>
          <router-link class="mui-tab-item" to="/settings">
            <span class="mui-icon mui-icon-gear"></span>
            <span class="mui-tab-label">设置</span>
          </router-link>
        </nav>
        <i></i>
      </footer>
    </template>
    
    <script>
    export default {};
    </script>
    
    <style scoped>
    i {
      display: block;
      height: 50px;
    }
    </style>
    
    • src/component/common/header.vue
    <template>
      <header>
        <mt-header fixed title="小买卖">
          <!-- 返回按钮只在非首页出现 -->
          <!-- 通过$route.path那到当前路径比较 -->
          <!-- 通过$router.go(-1)方法实现页面返回功能 -->
          <mt-button v-if="$route.path != '/index'" v-on:click="$router.go(-1)" icon="back" slot="left"></mt-button>
        </mt-header>
        <i></i>
      </header>
    </template>
    
    <script>
    export default {};
    </script>
    
    <style scoped>
    header i {
      display: block;
      height: 40px;
    }
    </style>
    
    • src/component/common/index.js
    // 编写属于自己的公共Vue组件库
    import HeaderComponent from './header.vue';
    import FooterComponent from './footer.vue';
    import NumboxComponent from './numbox.vue';
    
    // Vue插件要求提供一个install方法, 这个方法会被注入Vue
    // 需要我们调用Vue的filter component directive去扩展功能
    export default {
      install(Vue) {
        Vue.component('app-header', HeaderComponent);
        Vue.component('app-footer', FooterComponent);
        Vue.component('app-numbox', NumboxComponent);
      }
    };
    
    
    • src/component/common/numbox.vue
    <template>
      <div class="mui-numbox">
        <button class="mui-btn mui-btn-numbox-minus" @click="sub">-</button>
        <input class="mui-input-numbox" type="number" v-model="val">
        <button class="mui-btn mui-btn-numbox-plus" @click="add">+</button>
      </div>
    </template>
    
    <script>
    export default {
      props: ["initVal"],
    
      data() {
        return {
          val: this.initVal || 0 // 优先使用父指定的默认值, 父不指定默认为0
        };
      },
    
      methods: {
        // 减减, 最小值为0
        sub() {
          this.val > 0 && this.val--;
        },
    
        // 加加, 最大值不限
        add() {
          this.val++;
        }
      },
    
      watch: {
        // 值发生变化就通过事件的方式传给父
        val() {
          this.$emit("change", this.val);
        }
      }
    };
    </script>
    
    <style scoped>
    
    </style>
    
    • src/component/goods/son/intro.vue
    <template>
      <!-- 使用mui的卡片视图进行布局 -->
      <div class="mui-card">
        <div class="mui-card-header">{{ intro.title }}</div>
        <div class="mui-card-content">
          <div class="mui-card-content-inner" v-html="intro.content"></div>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      props: ["id"],
    
      data() {
        return {
          intro: {}
        };
      },
    
      methods: {
        // 获取图文介绍, 但是需要由父亲告诉我id
        getIntro() {
          this.axios
            .get(this.api.goodsD + this.id)
            .then(rsp => (this.intro = rsp.data.message[0]));
        }
      },
    
      created() {
        this.getIntro();
      }
    };
    </script>
    
    <style scoped>
    
    </style>
    
    • src/component/goods/goods_detail.vue
    <template>
      <article class="goods-detail">
        <!-- 轮播图 -->
        <mt-swipe :auto="10000">
          <!-- 我们这个商品缩略图是没有跳转连接的, 不需要router-link -->
          <mt-swipe-item v-for="item in lunbos" v-bind:key="item.src">
            <img v-bind:src="item.src">
          </mt-swipe-item>
        </mt-swipe>
    
        <!-- 商品购买 -->
        <div class="mui-card">
          <!-- 名称 -->
          <div class="mui-card-header">{{ goodsPrice.title }}</div>
          <!-- 价格 -->
          <div class="mui-card-content mui-card-content-inner">
            <div class="price">
              <s>市场价:¥{{ goodsPrice.market_price }}</s>
              <span>销售价: </span>
              <em>¥{{ goodsPrice.sell_price }}</em>
            </div>
            <div>
              <span>购买数量:</span>
              <!--数字输入框 -->
              <app-numbox v-bind:initVal="buyCount" @change="getTotal"></app-numbox>
            </div>
          </div>
          <!-- 按钮 -->
          <div class="mui-card-footer">
            <button type="button" class="mui-btn mui-btn-success mui-btn-block mui-btn-outlined">结算</button>
            <div></div>
            <button type="button" @click="addShopcart" class="mui-btn mui-btn-success mui-btn-block mui-btn-outlined">加入购物车</button>
          </div>
        </div>
    
        <!-- 评论与介绍 -->
        <div class="mui-card">
          <!-- 选项卡, 利用value的值控制选取那个子元素 -->
          <mt-navbar v-model="navbarSelector">
            <mt-tab-item id="commont">商品评论</mt-tab-item>
            <mt-tab-item id="intro">图文介绍</mt-tab-item>
          </mt-navbar>
          <!-- 内容, 利用value的值控制选取那个子元素 -->
          <mt-tab-container v-model="navbarSelector">
            <mt-tab-container-item id="commont">
              <p>内容1</p>
            </mt-tab-container-item>
            <mt-tab-container-item id="intro">
              <app-intro v-bind:id="id"></app-intro>
            </mt-tab-container-item>
          </mt-tab-container>
        </div>
    
      </article>
    </template>
    
    <script>
    import IntroComponent from "./son/intro.vue";
    import storage from "../../js/storage.js";
    
    export default {
      data() {
        return {
          id: this.$route.params.id,
          lunbos: [],
          goodsPrice: {},
          navbarSelector: "commont",
          buyCount: (storage.get("goodsBuyData") || {})[this.$route.params.id]
        };
      },
    
      methods: {
        // 获取商品缩略图
        getGoodsThumList() {
          this.axios
            .get(this.api.goodsT + this.id)
            .then(rsp => (this.lunbos = rsp.data.message));
        },
    
        // 获取商品价格信息
        getGoodsPrice() {
          this.axios
            .get(this.api.goodsP + this.id)
            .then(rsp => (this.goodsPrice = rsp.data.message[0]));
        },
    
        // 获取最新的购买数量, 并存储起来
        getTotal(total) {
          this.buyCount = total;
        },
    
        // 加入购物车
        addShopcart() {
          let oldBuyData = storage.get("goodsBuyData") || {}; // 取出旧的值
          oldBuyData[this.id] = this.buyCount; // 添加或修改商品的购买记录
          storage.set("goodsBuyData", oldBuyData); // 把新的数据存起来
        }
      },
    
      created() {
        this.getGoodsThumList();
        this.getGoodsPrice();
      },
    
      components: {
        "app-intro": IntroComponent
      }
    };
    </script>
    
    <style lang="less">
    .goods-detail {
      .mui-card-content {
        .price {
          color: rgb(51, 51, 51);
          margin-bottom: 4px;
          span {
            margin-left: 6px;
          }
          em {
            font-size: 18px;
            color: red;
          }
        }
      }
      .mui-card-footer {
        div {
          width: 100%;
        }
        .mui-btn {
          padding: 8px 0;
          font-size: 16px;
        }
      }
      .mint-tab-item {
        &.is-selected {
          margin-bottom: 0;
          border-bottom: 3px solid #2ce094;
          color: #2ce094;
        }
      }
      .mint-tab-item-label {
        font-size: 18px;
        color: #2ce094;
      }
    }
    // 给轮播图加个高度
    .mint-swipe {
      height: 260px;
      background-color: white;
      img {
        display: block;
        margin: 0 auto;
        max-width: 100%;
        height: 260px;
      }
    }
    </style>
    
    • src/component/goods/goods_list.vue
    <template>
      <article>
        <ul class="mui-table-view mui-grid-view">
          <!-- 商品详情 -->
          <li v-for="item in goodsList" v-bind:key="item.id" class="mui-table-view-cell mui-media mui-col-xs-6">
            <router-link v-bind:to="{ name: 'gd', params: { id: item.id } }">
              <div class="mui-card">
                <!-- 商品图片 -->
                <div class="mui-card-header">
                  <img v-bind:src="item.img_url" alt="" />
                </div>
                <!-- 商品描述 -->
                <div class="mui-card-footer ">
                  <p class="mui-ellipsis-2">{{ item.title }}</p>
                </div>
                <!-- 商品价格 -->
                <div class="mui-card-content">
                  <p class="price">
                    <span>¥{{ item.sell_price }}</span>
                    <s>¥{{ item.market_price }}</s>
                  </p>
                  <p class="tip">
                    <span>热卖中</span>
                    <span>剩余{{ item.stock_quantity }}件</span>
                  </p>
                </div>
              </div>
            </router-link>
          </li>
        </ul>
        <!-- 加载更多 -->
        <button v-on:click="loadMore()" v-bind:disabled="lastPage" class="mui-btn mui-btn-success mui-btn-block mui-btn-outlined">
          {{ lastPage? '已经是最后一页了': '加载更多' }}
        </button>
      </article>
    </template>
    
    <script>
    export default {
      data() {
        return {
          goodsList: [],
          pageIndex: 1,
          lastPage: false // 是否最后一页
        };
      },
    
      methods: {
        // 获取商品列表, 需要一个pageindex查询字符串, 用来指定页码
        getGoodsList() {
          this.axios
            .get(`${this.api.goodsL}?pageindex=${this.pageIndex}`)
            .then(rsp => {
              this.goodsList.push(...rsp.data.message);
              this.isLastPath(rsp.data.message);
            });
        },
    
        // 加载下一页数据
        loadMore() {
          this.pageIndex++;
          this.getGoodsList();
        },
    
        // 判断是不是最后一页数据, 是的话把lastPage设为ture
        isLastPath(goodsList) {
          if (goodsList.length == 0) {
            this.lastPage = true;
          }
        }
      },
    
      created() {
        this.getGoodsList();
      }
    };
    </script>
    
    <style lang="less" scoped>
    .mui-card {
      box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.3);
    }
    .mui-card-header {
      padding: 8px;
      /*height: 100px;*/
      img {
        width: 100%;
        height: 100%;
      }
    }
    .mui-card-content {
      text-align: center;
      .price {
        margin-bottom: 4px;
        color: #000;
        span {
          color: red;
        }
      }
      .tip {
        overflow: hidden;
        padding: 0 8px;
        font-size: 12px;
        span:first-child {
          float: left;
        }
        span:last-child {
          float: right;
        }
      }
    }
    </style>
    
    • src/component/home/home.vue
    <template>
      <article>
        <!-- 轮播图 -->
        <mt-swipe :auto="10000">
          <mt-swipe-item v-for="item in lunbos" v-bind:key="item.url">
            <router-link v-bind:to="item.url">
              <img v-bind:src="item.img">
            </router-link>
          </mt-swipe-item>
        </mt-swipe>
        <!-- 六宫格 -->
        <ul class="mui-table-view mui-grid-view mui-grid-9">
          <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
            <router-link to="/">
              <span class="mui-icon mui-icon-home"></span>
              <div class="mui-media-body">首页</div>
            </router-link>
          </li>
          <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
            <router-link to="/news/list">
              <span class="mui-icon mui-icon-chat"></span>
              <div class="mui-media-body">热点新闻</div>
            </router-link>
          </li>
          <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
            <router-link to="/photo/list/0">
              <span class="mui-icon mui-icon-image"></span>
              <div class="mui-media-body">图片分享</div>
            </router-link>
          </li>
          <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
            <router-link to="/">
              <span class="mui-icon mui-icon-search"></span>
              <div class="mui-media-body">搜索</div>
            </router-link>
          </li>
          <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
            <router-link to="/">
              <span class="mui-icon mui-icon-phone"></span>
              <div class="mui-media-body">联系我们</div>
            </router-link>
          </li>
          <li class="mui-table-view-cell mui-media mui-col-xs-4 mui-col-sm-3">
            <router-link to="/">
              <span class="mui-icon mui-icon-info"></span>
              <div class="mui-media-body">关于我们</div>
            </router-link>
          </li>
        </ul>
      </article>
    </template>
    
    <script>
    export default {
      data() {
        return {
          lunbos: []
        };
      },
    
      methods: {
        // 请求数据, 成功后把数据存储到lunbos中
        getLunbo() {
          this.axios
            .get(this.api.getLunbo)
            .then(rep => (this.lunbos = rep.data.message));
        }
      },
    
      // 组件初始化完毕后, 自动调用接口获取数据渲染轮播图
      created() {
        this.getLunbo();
      }
    };
    </script>
    
    <style lang="less" scoped>
    @height: 260px;
    article {
      height: @height;
      img {
        height: @height;
      }
    }
    </style>
    
    
    • src/component/news/news_detail.vue
    <template>
      <article>
        <!-- 使用mui的卡片视图布局, 注意: 卡片视图都是flex, 这里把他改成block -->
        <div class="mui-card">
          <div class="mui-card-header">
            <h4>{{ newsDetail.title }}</h4>
            <p class="mui-ellipsis">
              <span>创建时间: {{ newsDetail.add_time | date }}</span>
              <span>点击数: {{ newsDetail.click }}</span>
            </p>
          </div>
          <!-- content内容中含有html标签, 要让它正常展示, 必须使用v-html -->
          <div class="mui-card-footer" v-html="newsDetail.content"></div>
        </div>
      </article>
    </template>
    
    <script>
    export default {
      data() {
        return {
          newsDetail: {}
        };
      },
    
      methods: {
        // 获取新闻详情, 注意这里接口返回的是一个数组, 我们需要通过下标那新闻详情对象
        getNewsDetail() {
          this.axios
            .get(this.api.getND + this.$route.params.id)
            .then(rsp => (this.newsDetail = rsp.data.message[0]));
        }
      },
    
      created() {
        this.getNewsDetail();
      }
    };
    </script>
    
    <style scoped>
    article {
      overflow: hidden;
    }
    .mui-card-header,
    .mui-card-footer {
      display: block;
    }
    </style>
    
    • src/component/news/news_list.vue
    <template>
      <article>
        <ul class="mui-table-view">
          <li class="mui-table-view-cell mui-media" v-for="item in newsList" v-bind:key="item.id">
            <router-link v-bind="{ to: `/news/detail/${item.id}` }">
              <img class="mui-media-object mui-pull-left" v-bind:src="item.img_url">
              <div class="mui-media-body">
                <h4 class="mui-ellipsis">{{ item.title }}</h4>
                <p class="mui-ellipsis">
                  <span>创建时间: {{ item.add_time | date }}</span>
                  <span>点击数: {{ item.click }}</span>
                </p>
              </div>
            </router-link>
          </li>
        </ul>
      </article>
    </template>
    
    <script>
    export default {
      data() {
        return {
          newsList: []
        };
      },
    
      methods: {
        // 获取新闻列表数据
        getNewsList() {
          this.axios
            .get(this.api.getNL)
            .then(rsp => (this.newsList = rsp.data.message));
        }
      },
    
      // 上来就调用接口初始化数据
      created() {
        this.getNewsList();
      }
    };
    </script>
    
    <style scoped>
    
    </style>
    
    • src/component/photo/photo_detail.vue
    <template>
      <article>
        <!-- 使用mui的卡片视图布局, 注意: 卡片视图都是flex, 这里把他改成block -->
        <div class="mui-card">
          <div class="mui-card-header">
            <h4>{{ photoDetail.title }}</h4>
            <p class="mui-ellipsis">
              <span>创建时间: {{ photoDetail.add_time | date }}</span>
              <span>点击数: {{ photoDetail.click }}</span>
            </p>
          </div>
          <!-- 使用mui的图文表格布局 -->
          <ul class="mui-table-view mui-grid-view">
            <li class="mui-table-view-cell mui-media mui-col-xs-4" v-for="item in photoThumList" v-bind:key="item.src">
              <img class="mui-media-object" v-bind:src="item.src" v-preview="item.src">
            </li>
          </ul>
          <!-- content内容中含有html标签, 要让它正常展示, 必须使用v-html -->
          <div class="mui-card-footer">{{ photoDetail.content }}</div>
        </div>
      </article>
    </template>
    
    <script>
    export default {
      data() {
        return {
          id: this.$route.params.id,
          photoDetail: {},
          photoThumList: []
        };
      },
    
      methods: {
        // 获取图片详情
        getPhotoDetail() {
          this.axios
            .get(this.api.photoD + this.id)
            .then(rsp => (this.photoDetail = rsp.data.message[0]));
        },
    
        // 获取图片缩略图
        getphotoThumList() {
          this.axios
            .get(this.api.photoT + this.id)
            .then(rsp => (this.photoThumList = rsp.data.message));
        }
      },
    
      created() {
        this.getPhotoDetail();
        this.getphotoThumList();
      }
    };
    </script>
    
    <style scoped>
    .mui-card-header,
    .mui-card-footer {
      display: block;
    }
    .mui-card h4 {
      font-size: 14px;
    }
    </style>
    
    • src/component/photo/photo_list.vue
    <template>
      <article>
        <!-- 使用mui的列表布局 -->
        <ul class="mui-table-view">
          <li class="mui-table-view-cell">
            <router-link v-bind:to="{ name: 'pl', params: { id: 0 } }">全部</router-link>
          </li>
          <li v-for="item in photoCategoryList" v-bind:key="item.id" class="mui-table-view-cell">
            <router-link v-bind:to="{ name: 'pl', params: { id: item.id } }">{{ item.title }}</router-link>
          </li>
        </ul>
    
        <!-- 使用mui的卡片视图布局 -->
        <div class="mui-card" v-for="item in photoList" v-bind:key="item.id">
          <router-link v-bind:to="{ name: 'pd', params: { id: item.id } }">
            <div class="mui-card-header mui-card-media" v-bind="{ style: `height:40vw;background-image:url(${item.img_url})` }"></div>
            <div class="mui-card-content">
              <div class="mui-card-content-inner">
                <p>{{ item.title }}</p>
                <p style="color: #333;">{{ item.zhaiyao }}</p>
              </div>
            </div>
          </router-link>
        </div>
      </article>
    </template>
    
    <script>
    export default {
      data() {
        return {
          photoCategoryList: [],
          photoList: []
        };
      },
    
      methods: {
        // 获取图片分类列表
        getPhotoCategoryList() {
          this.axios
            .get(this.api.photoC)
            .then(rsp => (this.photoCategoryList = rsp.data.message));
        },
    
        // 获取图片列表, 需要使用分类ID来获取指定的图片列表
        getPhotoList() {
          this.axios
            .get(this.api.photoL + this.$route.params.id)
            .then(rsp => (this.photoList = rsp.data.message));
        }
      },
    
      // 在组件初始化完毕后执行一次
      created() {
        this.getPhotoCategoryList();
        this.getPhotoList();
      },
    
      watch: {
        // 监听url的变化, 变化后拿到新的id,
        // 调用接口发送请求修改photoList数据
        $route() {
          this.getPhotoList();
        }
      }
    };
    </script>
    
    <style lang="less" scoped>
    .mui-table-view {
      overflow: hidden;
      li {
        float: left;
        color: deepskyblue;
      }
    }
    
    .mui-card-header,
    .mui-card-header {
      display: block;
    }
    </style>
    
    • src/component/shopcart/shopcart.vue
    <template>
      <article class="shopcart-list">
    
        <!-- 商品列表 -->
        <div class="goods" v-for="item in buyGoodsList" v-bind:key="item.id">
          <mt-switch class="switch" v-model="item.isSelected"></mt-switch>
          <img class="img" v-bind:src="item.thumb_path">
          <div class="inforight">
            <h4 class="mui-ellipsis-2">{{ item.title }}</h4>
            <div class="bottom">
              <ul>
                <li>¥{{ item.sell_price }}</li>
                <li>
                  <!-- 公共的数字输入框, 修改商品数量需要拿到id与子传给父的值, 所以这里需要使用()传参, $event就代表子传父的数据 -->
                  <app-numbox v-bind:initVal="goodsBuyData[item.id]" @change="modifyBuyData(item.id, $event)"></app-numbox>
                </li>
                <li>
                  <a href="javascript:void(0)" @click="delGoods(item.id)">删除</a>
                </li>
              </ul>
            </div>
          </div>
        </div>
    
        <!-- 总价 -->
        <div class="total">
          <div class="total_val">
            <ul>
              <li>总计(不含运费)</li>
              <li>已勾选商品{{ buyTotal }}件,总价:¥品{{ buyPriceTotal }}元</li>
            </ul>
          </div>
          <div class="total_btn">
            <mt-button type="primary" @click="$store.commit('setBuyTotal', 888)">付 款{{ $store.state.buyTotal }}</mt-button>
          </div>
        </div>
    
      </article>
    </template>
    
    <script>
    import storage from "../../js/storage.js";
    
    export default {
      data() {
        return {
          goodsBuyData: storage.get("goodsBuyData"),
          buyGoodsList: []
        };
      },
    
      methods: {
        // 获取购物车列表数据
        getBuyGoodsList() {
          let ids = Object.keys(storage.get("goodsBuyData")).join(",");
          this.axios.get(this.api.shopcL + ids).then(rsp => {
            // 给每个商品补充一个isSelected属性, 默认值为true
            rsp.data.message.forEach(goods => (goods.isSelected = true));
            this.buyGoodsList = rsp.data.message;
          });
        },
    
        // 修改购买数据
        modifyBuyData(id, val) {
          this.goodsBuyData[id] = val;
          console.log(this.goodsBuyData);
        },
    
        // 删除商品
        delGoods(id) {
          this.$delete(this.goodsBuyData, id);
          this.buyGoodsList = this.buyGoodsList.filter(v => v.id != id);
        }
      },
    
      created() {
        this.getBuyGoodsList();
      },
    
      computed: {
        // 总数
        buyTotal() {
          return this.buyGoodsList.reduce((sum, goods) => {
            // reduce方法每次把上一次的sum结果传递进来, 供我们继续累加,
            // 如果商品为选中状态我们就累加, 否则原物传递到下一次计算
            return goods.isSelected ? sum + this.goodsBuyData[goods.id] : sum;
          }, 0);
        },
    
        // 总价
        buyPriceTotal() {
          return this.buyGoodsList.reduce((sum, goods) => {
            // reduce方法每次把上一次的sum结果传递进来, 供我们继续累加,
            // 如果商品为选中状态我们就累加, 否则原物传递到下一次计算
            return goods.isSelected
              ? sum + this.goodsBuyData[goods.id] * goods.sell_price
              : sum;
          }, 0);
        }
      },
    
      watch: {
        // 监听商品数量的变化, 实时存储的本地storage
        goodsBuyData: {
          handler() {
            storage.set("goodsBuyData", this.goodsBuyData);
          },
          // 深度监听对象的变化, 这样vue每次会比较子属性的值
          deep: true
        }
      }
    };
    </script>
    
    <style lang="less">
    .shopcart-list {
      .goods {
        border-bottom: 1px solid rgba(0, 0, 0, 0.3);
        height: 102px;
        display: flex;
        padding: 5px;
        .switch {
          flex: 0 0 52px;
        }
        .img {
          margin-left: 5px;
          height: 75px;
          width: 75px;
          flex: 0 0 85px;
        }
        .inforight {
          margin-left: 5px;
          flex: 1;
        }
        .inforight ul {
          padding-left: 0px;
        }
        .inforight li {
          list-style: none;
          display: inline-block;
        }
        .inforight h4 {
          color: #0094ff;
          font-size: 14px;
        }
        .bottom li:first-child {
          color: red;
          margin-right: 5px;
        }
        .bottom li:last-child {
          margin-left: 5px;
        }
      }
      .total {
        height: 84px;
        background-color: rgba(0, 0, 0, 0.1);
        display: flex;
        padding: 5px 14px;
        ul {
          padding-left: 0px;
          margin: 14px 0;
          li {
            list-style: none;
            font-size: 14px;
          }
        }
        &_val {
          flex: 1;
        }
        &_btn {
          flex: 0 0 60px;
          margin: 18px 0 0 0;
        }
      }
    }
    </style>
    
    
    • src/component/App.vue
    <template>
      <main>
        <lg-preview></lg-preview>
        <app-header></app-header>
        <router-view></router-view>
        <app-footer></app-footer>
      </main>
    </template>
    
    <script>
    export default {};
    </script>
    
    <style scoped>
    
    </style>
    
    • src/component/filter/date.js
    export default function(time) {
        let date = new Date(time);
        return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    };
    
    
    • src/component/filter/index.js
    import DateFilter from './date.js';
    
    export default {
        install(Vue) {
            Vue.filter('date', DateFilter);
        }
    };
    
    
    • src/component/js/api_config.js
    const domain = 'http://vue.studyit.io/api';
    
    export default {
    
      // 获取轮播图的接口
      getLunbo: `${domain}/getlunbo`,
    
      // 新闻相关接口
      getNL: `${domain}/getnewslist`,
      getND: `${domain}/getnew/`,             // 该接口后面需要一个id
    
      // 图片相关接口
      photoC: `${domain}/getimgcategory/`,
      photoL: `${domain}/getimages/`,      // 该接口后面需要一个分类id: /getimages/:id
      photoD: `${domain}/getimageinfo/`,   // 该接口后面需要一个图片id: /getimageinfo/:id
      photoT: `${domain}/getthumimages/`,  // 该接口后面需要一个图片id: /getthumimages/:id
    
      // 商品相关接口
      goodsL: `${domain}/getgoods/`,          // 该接口后面需要一个页码: /getgoods/?pageindex=number
      goodsD: `${domain}/goods/getdesc/`,     // 该接口后面需要一个商品id: /getdesc/:id
      goodsT: `${domain}/getthumimages/`,     // 该接口后面需要一个商品id: /getthumimages/:id
      goodsP: `${domain}/goods/getinfo/`,           // 该接口后面需要一个商品id: /getinfo/:id
    
      // 购物车相关接口
      shopcL: `${domain}/goods/getshopcarlist/`,  // 该接口后面需要一串id: /getshopcarlist/:ids
    
      // 评论相关接口
      commentL: `${domain}/getcomments/`,     // 该接口后面需要一个id: /getcomments/:id
      commentS: `${domain}/postcomment/`,     // 该接口后面需要一个id: /postcomment/:id, 该需要content内容
    };
    
    
    • src/component/js/main.js
    // from后面的路径, 如果含有./ ../那么就相对于当前文件找文件
    // 如果没有, 那么就会去node_modules里面找对应的包
    // 1.1 导入第三方包
    import Vue from 'vue';
    import MintUi from 'mint-ui';
    import 'mint-ui/lib/style.css';
    import Common from '../component/common';  // 自动找到index.js引入
    import 'mui/dist/css/mui.css';
    import 'mui/examples/hello-mui/css/icons-extra.css';
    import axios from 'axios';
    import VueRouter from 'vue-router';
    import Filter from '../filter'             // 自动找到index.js引入
    import '../less/index.less';
    import VuePP from 'vue-picture-preview';
    import Vuex from 'vuex';
    
    // 1.2 启用vue插件
    Vue.use(MintUi);
    Vue.use(Common);
    Vue.use(VueRouter);
    Vue.use(Filter);
    Vue.use(VuePP);
    Vue.use(Vuex);
    
    // 2.1 导入配置
    import routerConfig from '../router'    // 自动找到index.js引入
    import apiConfig from './api_config.js'
    
    // 2.2 扩展实例成员
    Vue.prototype.axios = axios;   // 把axios库放置到原型, 将来其他组件直接可以拿到axios对象
    Vue.prototype.api = apiConfig;
    
    // 2.3 导入根组件
    import AppComponent from '../component/App.vue';
    
    // 2.4 渲染根组件, 启动项目
    new Vue({
      el: '#app',
      render(createNode) {
        return createNode(AppComponent);
      },
      router: new VueRouter(routerConfig),
      store: new Vuex.Store({
    
        // 这个配置项就相当于咱们的data选项
        state: {
          buyTotal: 100
        },
    
        // 这个配置想就相当于咱们的methods选项, 用于定义一些方法, 
        // 但是这里的方法作用很明确就是为了修改状态值
        mutations: {
    
          // 这个方法的第一个参数为vuex自动传入, 即state状态
          // 这个方法的第二个参数为用户传入
          // 注意: 千万不要通过$store.state.buyTotal = newTotal这样方式修改值
          // 因为这样vuex无法捕获到数据的变化, 同时这个数据是共享的, 可能在任意地方被修改不利于维护
          // 如果调用这里方法修改数据, 不会混乱, 因为修改规则我都提取设计好了
          setBuyTotal(state, newTotal) {
            state.buyTotal = newTotal;
          }
    
        }
      })
    });
    
    
    
    • src/component/less/index.less
    export default {
    
      // localStorage.setItem的封装
      set(key, val) {
        localStorage.setItem(key, JSON.stringify(val));
      },
    
      // localStorage.getItem的封装
      get(key) {
        let val = localStorage.getItem(key);
        // 先尝试着解析数据, 成功了就返回解析后的值, 不成功就原物返回
        try {
          val = JSON.parse(val);
        } finally {
          return val;
        }
      },
    
      // 清除所有本地存储的数据
      clear() {
        localStorage.clear();
      }
    
    };
    
    
    • src/component/less/index.less
    .mui-card-footer img {
        width: 100%;
    }
    
    .mui-card img {
        width: 100%;
        height: auto;
    }
    
    • src/component/router/index.js
    // 这里对外导出一个路由配置对象
    import HomeComponent from '../component/home/home.vue';
    import NewsListComponent from '../component/news/news_list.vue';
    import NewsDetailComponent from '../component/news/news_detail.vue';
    import PhotoListComponent from '../component/photo/photo_list.vue';
    import PhotoDetailComponent from '../component/photo/photo_detail.vue';
    import GoodsListComponent from '../component/goods/goods_list.vue';
    import GoodsDetailComponent from '../component/goods/goods_detail.vue';
    import ShopcartComponent from '../component/shopcart/shopcart.vue';
    
    export default {
      linkActiveClass: 'mui-active',
      routes: [
        // 首页路由配置
        { path: "/", redirect: "/index" },
        { name: "i", path: "/index", component: HomeComponent },
    
        // 新闻路由配置
        { name: "nl", path: "/news/list", component: NewsListComponent },
        { name: "nd", path: "/news/detail/:id", component: NewsDetailComponent },
    
        // 图片分享相关路由
        { name: "pl", path: '/photo/list/:id', component: PhotoListComponent },
        { name: "pd", path: '/photo/details/:id', component: PhotoDetailComponent },
    
        // 商品相关路由
        { name: "gl", path: '/goods/list/', component: GoodsListComponent },
        { name: "gd", path: '/goods/detail/:id', component: GoodsDetailComponent },
    
        // 购物车相关路由
        { name: "sc", path: '/shopcart', component: ShopcartComponent },
      ]
    };
    
    
    • src/index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div id="app"></div>
    </body>
    </html>
    
    • .babelrc
    {
        "presets": [ "env" ],
        "plugins":["transform-runtime"]
    }
    
    
    • gitignore
    # 忽略第三方包, 他们已经记录在package.json文件中了
    /node_modules
    
    # 忽略打包后的文件, 因为我们的项目核心是源代码
    /dist
    
    # 忽略隐藏文件
    .* 
    
    # 不忽略git配置文件和babel配置文件
    !.gitignore
    !.babelrc
    
    • webpack.config.js
    const path = require('path');
    const HtmlWP = require('html-webpack-plugin');
    const CleanWP = require('clean-webpack-plugin');
    
    module.exports = {
      // 打包的入口文件
      entry: path.resolve(__dirname, './src/js/main.js'),
      // 输出
      output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'bundle.js'
      },
      // 插件配置
      plugins: [
        new HtmlWP({
          template: './src/index.html',
          filename: 'index.html',
          inject: 'body'
        }),
        new CleanWP(['dist'])
      ],
      // 模块配置
      module: {
    
        // 配置loader规则
        rules: [
    
          // css
          {
            test: /\.css$/,
            use: ['style-loader', 'css-loader']
          },
    
          // less
          {
            test: /\.less$/,
            use: ['style-loader', 'css-loader', 'less-loader']
          },
    
          // html
          {
            test: /\.(html|tpl)$/,
            use: ['html-loader']
          },
    
          // 静态资源引用
          {
            test: /\.(png|jpeg|gif|jpg|svg|mp3|ttf)$/,
            use: [
              { loader: 'url-loader', options: { limit: 10240 } } // 小于10KB的打包
            ]
          },
    
          // js
          {
            test: /\.js$/,
            use: ['babel-loader'],
            exclude: path.resolve(__dirname, '../node_modules')
          },
    
          // vue
          {
            test: /\.vue$/,
            use: ['vue-loader']
          }
    
        ]
      }
    };
    
    
    6. 执行webpack-dev-server:

    webpack-dev-server

    相关文章

      网友评论

          本文标题:09_02.vuex的使用

          本文链接:https://www.haomeiwen.com/subject/ubezvxtx.html