Skillful use of Vue.js+vuex to make a special collection of app_javascript techniques for the public number of micro-letters

Source: Internet
Author: User
Tags node server git clone

This article step-by-step to teach you how to use Vue.js + Vuex to create a special collection of micro-letter public number of the app

Project Address: Https://github.com/jrainlau/wechat-subscriptor

Download & Run

git clone git@github.com:jrainlau/wechat-subscriptor.git
CD Wechat-subscriptor && NPM Install

NPM Run dev//run in dev mode
CD backend-server && node crawler.js//Turn on the crawler server

Open ' localhost:8080 ' in your broswer and enjoy it.

Project Introduction
I focus on a number of public numbers in the micro-letter, often browsing the contents. But often when I read the article, is always interrupted by a variety of micro-letter messages, have to cut out, reply to the message, and then go back to the public number, reopen the article, cycle, annoyance. Later remembered that the micro-letter and Sogou have cooperation, you can search the dog directly through the public number, then why not use this resource to do a dedicated collection of public number application? This application can easily search the public number, and then collect it, when you want to see it directly open to see. Well, it's not difficult, so start thinking about the architecture.

Overall architecture

International practice, first look at the architecture chart:

Then the technology selection:

1. Use Sogou's API as the interface for querying public numbers.

2. Because of Cross-domain problems, interfaces are used through node crawlers.

3. Use Vue for development, Vuex for state management.

4. Use the MUI as a UI framework to facilitate future packaging into mobile apps.

5. Initialize the project using VUE-CLI and build it through Webpack.

First, analyze the Vuex part of the red circle. It is the core of the entire app and the center of all data processing.

All components of the client perform the processing of the incoming data (such as asynchronous requests) in the action, and then trigger the mutation to modify the state by the action, and then distribute it through the getter to the components to satisfy the "single Data Flow" feature, as well as the official recommendation Method:

After understanding the most important vuex, the other parts will be successful. Arrows indicate the flow of data, Localstorage is responsible for storing the contents of the favorites, easy to open the next time the application of the content will not be lost, the node server is responsible for crawling the keyword based on the data provided by the Sogou API.

Is it simple? Now let's start coding!

Initializing a project

NPM Install Vue-cli-g installs the latest version of VUE-CLI, then vue init webpack Wechat-subscriptor, and after a step-by-step setup and installation of the dependency pack, enter the directory of the project and make a slight change to the final directory structure as follows:

For details, please browse the project directly

Servers & Reptiles

Enter the/backend-server folder and create a new file named Crawler-server.js with the following code:

/*** crawler-server.js ***/' use strict ' const HTTP = require (' http ') const URL = require (' URL ') const UTIL = require (' U Til ') const superagent = require (' superagent ') const Cheerio = require (' cheerio ') const ONrequest = (req, res) => {/ /CORS Options Res.writehead ({' Content-type ': ' Text/plain ', ' access-control-allow-origin ': ' * '}) let KeyWord = Enco Deuri (Url.parse (Req.url, True). Query.query)//recieve keyword from the client side and use it to make requests if (KEYW ORD) {Let Resultarr = [] superagent.get (' http://weixin.sogou.com/weixin?type=1&query= ' + KeyWord + ' &ie=utf8&am

 P;_sug_=n&_sug_type_= '). End ((err, response) => {if (err) console.log (err) Let $ = cheerio.load (Response.text) $ ('. Mt7. Wx-rb '). Each ((index, item) => {//Define a object and update it//then push to the result array let ResU Ltobj = {title: ', Wxnum: ', Link: ', Pic: ',} resultobj.title = $ (item). Find (' H3 '). Text () Resultobj.wxn UM = $ (item). Find (' label'). Text () Resultobj.link = $ (item). attr (' href ') Resultobj.pic = $ (item). FIND (' img '). attr (' src ') resultarr.push ( Resultobj)} res.write (Json.stringify (Resultarr)) Res.end ()})} http.createserver (ONrequest). Listen (Process.en V.port | |

 8090) Console.log (' Server start! ')

A simple crawler, through the client-provided keywords to the Sogou to send requests, and then use Cheerio Analysis to obtain key information. Here is the search address of Sogou public number, you can try it yourself: http://weixin.sogou.com/

When the server is turned on, the content can be obtained only with the parameter request localhost:8090.

Using Vuex for state management
First Vuex official documents: http://vuex.vuejs.org/en/index.html

Believe me, do not read the Chinese version, or you will step on the pit, the English version is enough.

The previous schema diagram is aware that all data flow is through the Vuex, through the above document to understand the use of Vuex, we enter the/vuex folder to build the core Store.js code:

/*** store.js ***/

import Vue from ' Vue '
import Vuex to ' Vuex ' Vue.use

(VUEX)

const STATE = {
 Collec Titems: [],
 searchresult: {}
}

localstorage.getitem ("Collectitems")?
 State.collectitems = Localstorage.getitem ("Collectitems"). Split (', '):
 false

Const mutations = {
 set_ result [State, result] {
 State.searchresult = result
 },
 collect_it (state, name) {
 State.collectItems.push (name)
 Localstorage.setitem ("Collectitems", State.collectitems)
 },
 DELETE _collection (State, name) {
 State.collectItems.splice (state.collectItems.indexOf (name), 1)
 Localstorage.setitem ("Collectitems", State.collectitems)
 }
}

export default new Vuex.store ({
 State,
 mutations
})

Here we will focus on the code in the analysis.

First we define a state object in which two attributes correspond to the contents of the Favorites and search results. In other words, the entire app's data is stored in the state object, and it is used as a fetch.

Next, we define a mutations object. We can interpret mutations as "a series of methods used to change state states." In the concept of Vuex, state can only be modified by mutation, and the advantage is that it can be more intuitive to centrally manage the status of the application, rather than throwing the data everywhere.

It is not hard to see through the code that the three mutation functions are:

Set_result: Store search results in state

Collect_it: Adding to Favorites operations (including Localstorage)

delete_it: removing operations from favorites (including Localstorage)

Component Data Processing

Our app has a total of two components, Searchbar.vue and Searchresult.vue, which correspond to the search component and result part components respectively. Part of the search component contains the Favorites section, so it can also be understood as having three parts.

searching part of a component Searchbar.vue

/*** Searchbar.vue ***/


vuex: {getters
 : {
 Collectitem (state) {return
 state.collectitems
 }
 actions: {
 deletecollection: ({dispatch}, name) => {
 dispatch (' Delete_collection ', name)
 },< C11/>searchfun: ({dispatch}, keyword) => {
 $.get (' http://localhost:8090 ', {Query:keyword}, (data) => {
   dispatch (' Set_result ', Json.parse (Data)}}}}


The code is a bit long, this is focused only on the Vuex section, the complete code can refer to the project.

Getters gets the data from the store for use in the component.

The two methods of the actions are responsible for distributing the data to the store for mutation use.

In the official case, it seems to be complicated to call the action in the Assembly, but in fact it is possible to process the parameters through methods, and then pass the parameters in when the actions are triggered.

Result Part component Searchresult.vue

/*** Searchresult.vue ***/

vuex: {getters
 : {
 wordvalue (state) {return
 State.keyword
 },
 Collectitems (state) {return
 state.collectitems
 },
 SearchResult (state) {
 return State.searchresult
 }
 },
 actions: {
 Collectit: ({dispatch}, name, Collectarr) => {for
 ( Let item of Collectarr {
 if (item = name) return False
 }
 dispatch (' Collect_it ', name)
 }
 }
}

The result section is mainly to show that the place where the action is to be triggered is simply to add to the Favorites folder. Note that you should avoid duplicate additions, so you use the For...of loop, which is no longer added when the current element is already in the array.

End

The key logic part of the code analysis is complete, this app is also the thing, the UI part does not elaborate, see project source code or you DIY can. As for the package into the app, first you have to download Hbuilder, and then directly packaged through it can be, supporting the use of MUI can experience better results, do not know why so many people black it.

Sogou provides a very powerful API, but to remind, do not operate too frequently, or your IP will be it sealed off, I have been sealed ...

Weex has come out, through it can build native application, think is also excited ah, on the whim of the project made Weex version of the play ...

This article has been organized into the "Vue.js front-end component Learning course", "JavaScript micro-letter Development Skills Summary", welcome to learn to read.

For everyone to recommend now more attention than the micro-letter Program Tutorial: "Micro-letter Small Program Development tutorial" Small series for everyone carefully organized, hope like.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.