US group projects --- Change City 7

❤ source project ❤
GitHub address: https: //github.com/Umbrella001/mtapp

Change City

1.1 Implementation Figure

Here Insert Picture Description

1.2 assembly structure, a multi-page components are combined patchwork

Here Insert Picture Description

1.3 How do cities associating with?

Here Insert Picture Description
Here Insert Picture Description
After completion rely on E-UI interface, we began to write the logical interaction

The finished template:

<div class="m-iselect">
    <span class="name">按省份选择:</span>
    <el-select v-model="pvalue" placeholder="省份">
      <el-option
        v-for="item in province"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-select v-model="cvalue" :disabled="!city.length" placeholder="城市">
      <el-option v-for="item in city" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    <span class="name">&nbsp;&nbsp;&nbsp;&nbsp;中文搜索:</span>
    <el-autocomplete
      v-model="input"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入城市中文或拼音"
      @select="handleSelect"
    ></el-autocomplete>
  </div>

First, clear a city loaded switch interface, which is to be requested, and that is the provinces (the first stage), then you can use server-side ssr be rendered after the page loads followed were loaded, but here it is used directly vue in Mouted life complete function here axios request ↓

mounted: async function() {
    let self = this;
    let {
      status,
      data: { province }
    } = await self.$axios.get("/geo/province");
    if (status === 200) {
      self.province = province.map(item => {
        return {
          value: item.id,
          label: item.name
        };
      });
    }
  }

As a ready to complete the level, and then select the two urban areas in the province have no choice when the trigger is not, so you can use E-UI disable the ban were selected;

Well, we started to do the linkage logic, using the watch monitor what the user has selected provinces ↓

watch: {
    pvalue: async function(newPvalue) {
      let self = this;
      let {
        status,
        data: { city }
      } = await self.$axios.get(`/geo/province/${newPvalue}`);
      if (status === 200) {
        self.city = city.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
        self.cvalue = "";
      }
    }
  }

This data (the data determined by the user), you need to use the watch to listen, as long as the function is written on the inside has changed will be executed, and here you can just use the value of v-model binding as the value of listening , when the user selects asynchronous interfaces will request the provinces, pay attention to where the value passed with listening pvalue is the same, according to the request can be mounted to know pvalue is the corresponding provincial id, you might ask, then I v-model is bound the value of the input box, obviously there's a request parameter is not Chinese names Yeah, attention is the design select drop-down box here, if you do not set the label display or for value, but if you set up a label that input box shown is the label value, but you get the v-model or do you value the value , so the copy is the id assigned to the value in the provinces, so the parameters are correct!
Will be associating with, three linkage will be difficult? After all, you only need to focus on logical thinking of code, and DOM structure E-UI has casually completed, leaving only their code associated with your

1.4 How to use Element-UI to complete the project in a remote search?

Analysis:
all projects involving regions, there are certainly remote search, says that once the user searches mentioned Always use the throttle delay treatment, generally the throttle handle real-time search, now I know you can use lodash in delay function debounce

Remote search parameters analysis:
First, let's explain the DOM properties of the remote search E-UI is, only you understand the meaning of his above function node attributes you can go write logic, first of all v-model="input"who is binding, not the input box is slightly; `querySearchAsync` when the user input trigger, where you can write an interface request parameter;handleSelect trigger when selected

Important little talk:
① Delay function is asynchronous, anyway, give me write asynchronous function return values, so the argument is clear, there must be a return value (here, a reference to the search term, the second parameter is the callback return value)

② Those who still conditional array screening gave me write filter on the bin, there is no written es6 filter is bullying!

③ If the array is not conditional screening also need to traverse, map + arrow function to find out

④ out on the corresponding data according to user searches in English or Chinese can search for (upgrades available Pinyin)

methods: {
    querySearchAsync: _.debounce(async function(query, callback) {
      let self = this;
      if (self.cities.length) {
        callback(self.cities.filter(item => item.value.indexOf(query) > -1 || item.charValue.indexOf(query) > -1));
      } else {
        let {
          status,
          data: { city }
        } = await self.$axios.get("/geo/city");
        if (status === 200) {
          self.cities = city.map(item => {
            return {
              value: item.name,
              charValue: pyjs.getFullChars(item.name).toLocaleLowerCase()
            };
          });
          callback(self.cities.filter(item => item.value.indexOf(query) > -1 || item.charValue.indexOf(query) > -1));
        } else {
          callback([]);
        }
      }
    }, 200),

About showcase the city's popular bar that logic and DOM structure is very simple, brief refresher:

First talk about the structure of the DOM structure requires only a few DOM node is complete:
DL> dd dt +

  <div class="m-hcity">
    <dl>
      <dd>热门城市:</dd>
      <dt 
        v-for="item in list" 
        :key="item.id"
      >{{item.name === '市辖区'? item.province: item.name}}</dt>
    </dl>
  </div>

Second is the logic, since it is used to take advantage of nuxt async and await requests mating interfaces:
here to emphasize two points:
① Mounted async () {} and mounted: async function () {} is the same

② with so many times deconstructed version of the assignment request interface, you should know what state {} is to put the braces, look at the following chart, do not know if looking through a request before ~!
Here Insert Picture Description

1.5 Classification according to the first letter of the city

Focus: on the first letter of alphabet city classified by two One is the backend to give you the help you identify a classification (generally small, not as good as the rear end on their own), and the second is how to do their own front-end ( focus on learning !!!)

Important points:

① the use of third-party plug-in library, currently the single most convenient way npm install js-pinyin, you can import where needed to use the plug-inimport pyjs from 'js-pinyin'

② on cycle 26 letters, how would you do? The array a write you, first of all DOM structure using a loop is definitely a must, this is is how to design your loop array ↓ entire string written AZ then split into an array

    <div>
   		 <!-- 字母导航栏 -->
        <dl class="m-categroy">
            <dt>按拼音首字母选择:</dt>
            <dd
              v-for="item in list"
              :key="item"
            >
                <a :href="'#city-' + item">{{ item }}</a>
            </dd>
        </dl>
        <!-- 字母城市展示栏 -->
        <dl 
          v-for="item in block" 
          :key="item.title" 
          class="m-catagroy-section">
            <dt :id="'city-' + item.title">{{item.title}}</dt>
            <dd>
                <span
                  v-for="c in item.city"
                  :key="c"
                >
                {{ c }}
                </span>
            </dd>
        </dl>
    </div>
 data(){
        return{
            list:'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
        }
    }

How ③ combined js-pinyin plug-in library of data to get the Chinese spelling

There is a method plug-in library for getFullChars, it accepts the argument that Chinese data, the return value is the data corresponding to the Chinese spelling
PS: Note getFullChars got the A (Beijing: BeiJing) first letter capitalized, so according to the needs a full turn upper or lower case, also can match split by Ascll value to get the first letter capitalized, in short, to write logic can be based on demand

pyjs.getFullChars(item.name).toLocaleLowerCase().slice(0,1);

④ how to map the city into an array corresponding to the letter?

Only need to determine if this passage to get away, how to achieve?

First, do some simple code value az judge Ascrll lowercase letters (how come? By string.charCodeAt (0) got the first ASCLL value of the character)

Then determine whether the key name → If you do not create an empty object is stored in a key-value pair cityCharAll objects | OR | if there is a direct push into the existing array

Qiao here in memory of the object with the name of a key , and then let the same city beginning with the letter of the alphabet into the array corresponding Push in! perfect

if(cityAscll >= 97 && cityAscll <= 124){
     if(!cityCharAll[cityChar]){
         cityCharAll[cityChar] = []
     }
     cityCharAll[cityChar].push(item.name)
 }

Here Insert Picture Description
⑤ Through the above condemnation, but has not yet sorted, arranged az how it?

Why suddenly write, which is based on an array of DOM structure to design, anyway elements of the page to be recycled, will be put into circulation in the array to give them

 for(let [key,value] of Object.entries(cityCharAll)){
     blocks.push({
         title: key.toUpperCase(),
         city: value
     })
 }

The results are as follows:
Here Insert Picture Description
Sort:

 blocks.sort((x,y) => x.title.charCodeAt(0) - y.title.charCodeAt(0));
 self.block = blocks;

Sign ASCLL directly by the line code, sort () will automatically be in ascending order from small to large

Vue in jump (Jump according letters):

Prior to the height to do with the scroll, in fact, do not have to complete with JS, DOM can be used directly

Add a # anchor on the line! It is unclear see above DOM. Here because it involves dynamic data, so to addv-bind:href='xxx' ```→```→```→```→```→```:id='xxx'

<a href="#city-A">A</a>

<div id="city-A">A字母</div>

A click on the letters so you can jump to the beginning of the corresponding A list of cities

❤ source project ❤
GitHub address: https: //github.com/Umbrella001/mtapp

Published 134 original articles · won praise 80 · views 30000 +

Guess you like

Origin blog.csdn.net/Umbrella_Um/article/details/100191306