preface

Forward! Forward! Advance by hook or crook!!

It has been over half a month since the release of Vue3.0 beta. This should have been written last month, because the company was busy with the project last month. Took advantage of labor Day to write this thing, also incidentally some holes over once.

introduce

The page is relatively simple, and you’ve overdone the Composition API

  • Based on theVue3.0 betaThis kind of page also comparesoldthe
  • Involved in theVue3.0 beta and Vuex4 beta and axios

Install the VUE3 environment

Digression: heard that vite is good, these days have to understand 🤪

  1. Install (upgrade) the most recentvue-cli
  2. vue create projectNamePs: If you cannot manually installvuex4orvue-router4It is best to install all of these libraries directly (to reduce the time cost of trampling).
  3. vue add vue-nextThis command will automatically upgrade some of the dependencies in the project to a version that supports VUE3
  4. npm run serve

Composition-API

Vue-composition-api-rfc.netlify. app/#summary

🤐 directly paste the code

After all, the train of thought is similar, if you can suggest directly see github.com/notbucai/vu…

useScroll

import { ref } from 'vue';
export const useScrollTop = () => {
  const top = ref(0);
  window.addEventListener('scroll', () => {
    const scrollTop = document.documentElement.scrollTop;
    top.value = scrollTop;
  });
  return top;
}
Copy the code

store

import { createStore } from "vuex";

exportDefault createStore({state: {shopCart: {}, foodList: [],}, getters: {// TODO: where the amount calculated is"Something is wrong"Settlement (state) {settlement(state) {let allPrice = 0;
      letallCount = 0; const shopcart = state.shopcart; const foodList = state.foodList; // Get a list of all foods const foods = foodlist. reduce((previousValue, currentValue) => {returnpreviousValue.concat(currentValue.foods); } []); Object.keys(shopcart). ForEach (key => {const count = shopcart[key];if(! count)return; const food = foods.find(item => item.item_id == key); const price = food.specfoods[0].price; AllPrice += (price * 10000 * count); allPrice += (price * 10000 * count); allPrice = (price * 10000 * count); allCount += count; });return {
        price: allPrice / 10000,
        count: allCount,
      }
    }
  },
  mutations: {
    ADD_ITEM(state, id) {
      state.shopcart[id] = state.shopcart[id] || 0;
      state.shopcart[id]++;
    },
    SUB_ITEM(state, id) {
      state.shopcart[id] = state.shopcart[id] || 0;
      state.shopcart[id]--;
    },
    SET_FOOD_LIST(state, payload) {
      state.foodList = payload;
    }
  },
  actions: {
    setFoodList({ commit }, payload) {
      commit('SET_FOOD_LIST', payload)
    },
    addItem({ commit }, id) {
      commit('ADD_ITEM', id)
    },
    subItem({ commit }, id) {
      commit('SUB_ITEM', id)
    },
  }
});
Copy the code

page

<template>
  <div class="Catering">
    <header class="header">
      <div class="shop">
        <div class="shop-pic">
          <img
            src="https://upload.jianshu.io/users/upload_avatars/7759683/995f635d-357b-4539-b008-55aa6b0ac140.jpg?imageMogr2/auto-orient/ strip|imageView2/1/w/96/h/96/format/webp"
            alt
          />
        </div>
        <div class="shop-name"> a bag of rice </div> <div class="navbar">
        <div class="nav-item"> order </div> <div class="nav-item"> evaluate </div> <div class="nav-item"> Business </div> </div> <div class="outher-box"></div>
    </header>
    <main class="main">
      <div class="left">
        <div
          class="left-item"
          v-for="(item, index) in list"
          :class="{active:elIndex == index}"
          :key="index"
          @click="srcollTo(index)"
        >{{item.name}}</div>
      </div>
      <div class="right">
        <template v-for="(_item, index) in list"> <! <div :key= ref (div)"index" :ref="el=>itemEls[index] = el">
            <food-item :item="_item" />
          </div>
        </template>
      </div>
    <settlement-bottom />
    </main>
  </div>
</template>
<script>
import { watch, ref, onBeforeUpdate, onMounted, computed } from 'vue';
import { useStore } from 'vuex';
import { useScrollTop } from '.. /hooks';
import { getList } from '.. /ajax/index';
import FoodItem from './components/FoodItem';
import SettlementBottom from './components/SettlementBottom';

export default {
  components: { FoodItem, SettlementBottom },
  setup() { // store const store = useStore(); const list = computed(() => store.state.foodList); OnMounted (async () => {// NOTE: retrieve dataletresList = await getList(); // store store.dispatch('setFoodList', resList); }); Const itemEls = ref([]); // Const elIndex = ref(0); // Listen to data const scrollTop = useScrollTop([]); OnBeforeUpdate (() => {// Clears itemels. value = [] when updating; }); // Watch (scrollTop, () => {letindex = 0; ForEach ((el, I) => {// console.log() {// console.log() {// console.log() {// console.log();'el=>',el,'val=>', scrollTop.value);
        if (el.offsetTop > scrollTop.value) return; index = i; }); Elindex. value = index; }); const srcollTo = index => { elIndex.value = index; const el = itemEls.value[index]; const offsetTop = el.offsetTop; window.scrollTo(0, offsetTop); };return{ list, itemEls, elIndex, srcollTo }; }}; </script> <style lang="scss">... </style>Copy the code

FoodItem.vue

<template>
  <div class="FoodItem">
    <div class="food-title">{{item.name}}</div>
    <div class="food-item" v-for="(food) in item.foods" :key="food.item_id">
      <div class="food-pic">
        <img
          src="https://upload.jianshu.io/users/upload_avatars/16175630/e2ee85e5-7cb0-429d-a517-bb1c6f1833e4? imageMogr2/auto-orient/strip|imageView2/1/w/80/h/80/format/webp"
          alt
        />
      </div>
      <div class="food-main">
        <div class="food-info">
          <div class="title">{{food.name}}</div>
          <div class="info">{{food.applicable_quantity_text}}</div>
        </div>
        <div class="money"> selections {{food. Specfoods [0]. Price}} < / div > < / div > < div class ="food-action">
        <div class="action-item minus" v-if="shopcart[food.item_id]" @click="handleMinus(food)">-</div>
        <div class="action-num" v-if="shopcart[food.item_id]">{{shopcart[food.item_id]}}</div>
        <div class="action-item puls" @click="handlePuls(food)">+</div>
      </div>
    </div>
  </div>
</template>
<script>
// import { reactive, unref } from 'vue';
import { useStore } from 'vuex';
import { computed } from 'vue';
export default {
  components: {},
  props: {
    item: Object
  },
  setup() { // store const store = useStore(); // Shopping cart const shopcart = computed(() => store.state.shopcart); const handleChangeCount = (food,type) => {
      const id = food.item_id;
      const actionName = type> 0?'addItem' : 'subItem';
      store.dispatch(actionName, id);
    };

    const handleMinus = food => {
      handleChangeCount(food, -1);
    };
    const handlePuls = food => {
      handleChangeCount(food, 1);
    };

    return{ shopcart, handleMinus, handlePuls }; }}; </script> <style lang="scss" scoped>
......
</style>
Copy the code

SettlementBottom.vue

<template>
  <div class="SettlementBottom">
    <div class="num_box">x{{settlement.count}}</div>
    <div class="price_box"> selections {{settlement. Price}} < / div > < div class ="submit_btn" @click="handleSubmit"</div> </div> </template> <script> import {useStore} from'vuex';
import { computed } from 'vue';
export default {
  props: {},
  setup() {
    const store = useStore();
    const settlement = computed(() => store.getters.settlement);
    const handleSubmit = () => {
      const sc = store.state.shopcart;
      const shopcart = Object.keys(sc).map(key => ({
        id: key,
        count: sc[key]
      }));

      console.log('shopcart=>', shopcart);
      console.log('If you need the parameters of the original food, you can go directly to the state.');
    };
    return{ settlement, handleSubmit }; }}; </script> <style lang="scss" scoped>
......
</style>
Copy the code

github notbucai

notbucai blog