一步一步教你用Vue.js + Vuex制作專門收藏微信公眾號的app
只看不贊,或者只收藏不贊的都是耍流氓,放學別走,我找我哥收拾你們。
項目地址: https://github.com/jrainlau/wechat-subscriptor
下載&運行
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.
項目介紹
我在微信上關注了不少的公眾號,經常瀏覽里面的內容。但是往往在我閱讀文章的時候,總是被各種微信消息打斷,不得不切出去,回復消息,然后一路點回公眾號,重新打開文章,周而復始,不勝其煩。后來想起,微信跟搜狗有合作,可以通過搜狗直接搜索公眾號,那么為什么不利用這個資源做一個專門收藏公眾號的應用呢?這個應用可以方便地搜索公眾號,然后把它收藏起來,想看的時候直接打開就能看。好吧,其實也不難,那就開始從架構開始構思。
整體架構
國際慣例,先看架構圖:
然后是技術選型:
-
利用搜狗的API作為查詢公眾號的接口。
-
由于存在跨域問題,遂通過 node 爬蟲使用接口。
-
使用 vue 進行開發, vuex 作狀態管理。
-
使用 mui 作為UI框架,方便日后打包成手機app。
-
使用 vue-cli 初始化項目并通過 webpack 進行構建。
首先分析紅圈中的 vuex 部分。它是整個APP的核心,也是所有數據的處理中心。
客戶端所有組件都是在 action 中完成對流入數據的處理(如異步請求等),然后通過 action 觸發 mutation 修改 state ,后由 state 經過 getter 分發給各組件,滿足“單項數據流”的特點,同時也符合官方推薦的做法:
理解完最重要的 vuex 以后,其他部分也就順利成章了。箭頭表示數據的流動, LocalStorage 負責儲存收藏夾的內容,方便下一次打開應用的時候內容不會丟失,node服務器負責根據關鍵字爬取搜狗API提供的數據。
是不是很簡單?下面讓我們一起來開始coding吧!
初始化項目
npm install vue-cli -g 安裝最新版的 vue-cli ,然后 vue init webpack wechat-subscriptor ,按提示經過一步步設置并安裝完依賴包以后,進入項目的目錄并稍作改動,最終目錄結構如下:
具體的內容請直接瀏覽 項目
服務器&爬蟲
進入 /backend-server 文件夾并新建名為 crawler-server.js 的文件,代碼如下:
/*** 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!')
一個簡單的爬蟲,通過客戶端提供的關鍵詞向搜狗發送請求,后利用 cheerio 分析獲取關鍵的信息。這里貼上搜狗公眾號搜索的地址,你可以親自試一試: http://weixin.sogou.com/
當開啟服務器以后,只要帶上參數請求 localhost:8090 即可獲取內容。
使用 Vuex 作狀態管理
先貼上 vuex 官方文檔: http://vuex.vuejs.org/en/index.html
相信我,不要看中文版的,不然你會踩坑,英文版足夠了。
從前文的架構圖可以知道,所有的數據流通都是通過 vuex 進行,通過上面的文檔了解了有關 vuex 的用法以后,我們進入 /vuex 文件夾來構建核心的 store.js 代碼:
/*** 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
})
下面我們將對當中的代碼重點分析。
首先我們定義了一個 state 對象,里面的兩個屬性對應著收藏夾內容,搜索結果。換句話說,整個APP的數據就是存放在 state 對象里,隨取隨用。
接著,我們再定義一個 mutations 對象。我們可以把 mutations 理解為“用于改變 state 狀態的一系列方法”。在 vuex 的概念里, state 僅能通過 mutation 修改,這樣的好處是能夠更直觀清晰地集中管理應用的狀態,而不是把數據扔得到處都是。
通過代碼不難看出,三個 mutation 的作用分別是:
-
SET_RESULT :把搜索結果存入 state
-
COLLECT_IT :添加到收藏夾操作(包括 localstorage )
-
DELETE_IT :從收藏夾移除操作(包括 localstorage )
組件數據處理
我們的APP一共有兩個組件, SearchBar.vue 和 SearchResult.vue ,分別對應著搜索部分組件和結果部分組件。其中搜索部分組件包含著收藏夾部分,所以也可以理解為有三個部分。
-
搜索部分組件 SearchBar.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))
})
}
}
}
代碼有點長,這里僅重點介紹 vuex 部分,完整代碼可以參考 項目 。
getters 獲取 store 當中的數據作予組件使用。
actions 的兩個方法負責把數據分發到 store 中供 mutation 使用。
看官方的例子,在組件中向 action 傳參似乎很復雜,其實完全可以通過 methods 來處理參數,在觸發 actions 的同時把參數傳進去。
-
結果部分組件 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)
}
}
}
結果部分主要在于展示,需要觸發 action 的地方僅僅是添加到收藏夾這一操作。需要注意的地方是應當避免重復添加,所以使用了 for...of 循環,當數組中已有當前元素的時候就不再添加了。
尾聲
關鍵的邏輯部分代碼分析完畢,這個APP也就這么一回事兒,UI部分就不細說了,看看項目源碼或者你自己DIY就可以。至于打包成APP,首先你要下載HBuilder,然后通過它直接打包就可以了,配套使用 mui 能夠體驗更好的效果,不知道為什么那么多人黑它。
搜狗提供的API很強大,但是提醒一下,千萬不要操作太過頻繁,不然你的IP會被它封掉,我的已經被封了……
Weex 已經出來了,通過它可以構建Native應用,想想也是激動啊,待心血來潮就把本文的項目做成 Weex 版本的玩玩……
最后的最后,感謝你的閱讀,如果覺得我的文章不錯,歡迎關注我的專欄,下次見!
來自: https://segmentfault.com/a/1190000005844155