Don’t go after school. I’ll ask my brother to deal with you.
Project address: github.com/jrainlau/we…
Download & Run
git clone [email protected]: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.Copy the code
Project introduction
I follow a lot of public accounts on wechat and often browse the contents. But often when I read the article, I was always interrupted by various wechat messages, and I had to cut out, reply to the message, and then click back to the official account, re-open the article, again and again, very annoying. Later remembered, wechat with sogou cooperation, can be searched through sogou directly public number, so why not use this resource to do a special collection of public number application? The app makes it easy to search public accounts, and then bookmark them so you can open them whenever you want. Well, it’s not that hard, so start with the architecture.
The overall architecture
International practice, first look at the architecture diagram:
Then is the technology selection:
-
Use sogou API as the interface to query the public number
-
Because of the cross-domain problem, the interface is used through node crawler
-
Using VUE for development, vuEX for state management
-
Use MUI as a UI framework for later packaging into mobile apps
-
Initialize the project with VUe-CLI and build it with WebPack
First analyze the vuEX part in the red circle. It is the core of the APP and the processing center for all data.
All components of the client complete processing of incoming data (such as asynchronous request, etc.) in action, and then trigger mutation modification state through action, and then the state is distributed to each component through getter, which meets the characteristics of “single data flow” and also conforms to the official recommended practice:
Once you understand the most important part of the VUEX, the rest will follow. The arrow represents the flow of data. LocalStorage is responsible for storing the content of favorites, so that the content will not be lost when the application is opened next time. Node server is responsible for crawling the data provided by Sogou API according to the keywords.
Isn’t that easy? Let’s start coding together.
Initialize the project
NPM install vue-cli -g install the latest version of vue-cli, then vue init webpack Weike-subscriptor, as prompted after step by step setting and installing the dependency package, enter the project directory and make some changes, the final directory structure is as follows:
For details, please browse the project directly
Server & Crawler
Go to the /backend-server folder and create a file named crawler-server.js as follows:
/*** crawler-server.js ***/ 'use strict' const http = require('http') const url = require('url') const util = require('util') const superagent = require('superagent') const cheerio = require('cheerio') const onRequest = (req, res) => { // CORS options res.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*'}) let keyWord = encodeURI(url.parse(req.url, true).query.query) // recieve keyword from the client side and use it to make requests if (keyWord) { let resultArr = [] superagent.get('http://weixin.sogou.com/weixin?type=1&query=' + keyWord + '&ie=utf8&_sug_=n&_sug_type_=').end((err, response) => { if (err) console.log(err) let $ = cheerio.load(response.text) $('.mt7 .wx-rb').each((index, item) => { // define an object and update it // then push to the result array let resultObj = { title: '', wxNum: '', link: '', pic: "', } resultObj.title = $(item).find('h3').text() resultObj.wxNum = $(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.env.PORT || 8090) console.log('Server Start! ')Copy the code
A simple crawler sends requests to Sogou through keywords provided by the client, and then uses Cheerio analysis to obtain key information. Here post sogou public number search address, you can personally try: weixin.sogou.com/
When the server is started, simply request localhost:8090 with the parameter to get the content.
useVuex
State management
Vuex affixed first official documentation: vuex.vuejs.org/en/index.ht… Trust me, don’t read the Chinese version or you’ll step on the wrong sidethe English version is enough.
As you can see from the architecture diagram above, all the data flow is through vuex. With the above documentation about the use of vuex, we go to the /vuex folder to build the core store.js code:
/*** store.js ***/
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
collectItems: [],
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
})Copy the code
We’ll focus on the code in the current section.
First, we define a state object with two properties corresponding to favorites and search results. In other words, the entire APP’s data is stored in the State object, which is available at will.
Next, we define a mutations object. Mutations can be understood as “a series of methods used to change the state of the country.” In the vuEX concept, state can only be modified by mutation, which has the benefit of centrally managing application state more intuitively and clearly, rather than throwing data all over the place.
It is not difficult to see from the code that the effects of the three mutations are as follows:
-
SET_RESULT: Stores search results to state
-
COLLECT_IT: Add to favorites operation (including localstorage)
-
DELETE_IT: Remove operation from favorites (including localstorage)
Component data processing
Our APP has two components: Searchbar. vue and SearchResult.vue, which correspond to the search part and the result part respectively. The search component contains the favorites section, so it can also be interpreted as having three sections.
Search partial componentsSearchBar.vue
/*** SearchBar.vue ***/
vuex: {
getters: {
collectItem(state) {
return state.collectItems
}
},
actions: {
deleteCollection: ({ dispatch }, name) => {
dispatch('DELETE_COLLECTION', name)
},
searchFun: ({ dispatch }, keyword) => {
$.get('http://localhost:8090', { query: keyword }, (data) => {
dispatch('SET_RESULT', JSON.parse(data))
})
}
}
}Copy the code
The code is a little long, here only focuses on the VUEX part, the complete code can refer to the project.
-
Getters gets data from the store for use by the component
-
The two methods of Actions are responsible for distributing data to the store for mutation
In the official example, passing parameters to actions in a component may seem complicated, but you can use methods to handle parameters and pass them in while triggering actions.
Result part componentSearchResult.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)
}
}
}Copy the code
The results section is mostly for presentation, and the only action that needs to be triggered is the add to favorites action. Note that you should avoid repeating additions, so use for… The of loop, which stops adding the current element to the array when it already exists.
The end of the
The key logic part of the code analysis is finished, this APP is such a thing, THE UI part will not be detailed, look at the project source code or your own DIY can. As for packaging as an APP, you need to download HBuilder first and then package it directly. Mui will give you a better experience. I don’t know why so many people hack it.
Sogou provides a very powerful API, but remind you, do not operate too frequently, or your IP will be it sealed off, I have been sealed…
Weex has come out, through which you can build Native applications, it is also exciting to think about it, when the whim of the project into Weex version of play……
Finally, thank you for reading, if you think my article is good, welcome to pay attention to my column, see you next time!