一步一步教你用 Vue.js + Vuex 制作专门收藏微信公众号的 app

wpsowerfnc 8年前
   <p><img src="https://simg.open-open.com/show/f2a873daaf9428f4ade2798d62061674.gif"></p>    <p><img src="https://simg.open-open.com/show/8ddadd10d6a458a5d145572d7634ff6d.gif"></p>    <h2>下载&运行</h2>    <pre>  <code class="language-javascript">gitclone git@github.com:jrainlau/wechat-subscriptor.git  cdwechat-subscriptor && npminstall     npmrundev  // run in dev mode  cdbackend-server && nodecrawler.js  // turn on the crawler server     open `localhost:8080` in yourbroswerand enjoyit.  </code></pre>    <h2>项目介绍</h2>    <p>我在微信上关注了不少的公众号,经常浏览里面的内容。但是往往在我阅读文章的时候,总是被各种微信消息打断,不得不切出去,回复消息,然后一路点回公众号,重新打开文章,周而复始,不胜其烦。后来想起,微信跟搜狗有合作,可以通过搜狗直接搜索公众号,那么为什么不利用这个资源做一个专门收藏公众号的应用呢?这个应用可以方便地搜索公众号,然后把它收藏起来,想看的时候直接打开就能看。好吧,其实也不难,那就开始从架构开始构思。</p>    <h2>整体架构</h2>    <p>国际惯例,先看架构图:</p>    <p><img src="https://simg.open-open.com/show/2bd0fcfa5272b6457c085412c77c6d8b.jpg"></p>    <p>然后是技术选型:</p>    <ol>     <li>利用搜狗的API作为查询公众号的接口</li>     <li>由于存在跨域问题,遂通过 node 爬虫使用接口</li>     <li>使用 vue 进行开发, vuex 作状态管理</li>     <li>使用 mui 作为UI框架,方便日后打包成手机app</li>     <li>使用 vue-cli 初始化项目并通过 webpack 进行构建</li>    </ol>    <p>首先分析红圈中的 vuex 部分。它是整个APP的核心,也是所有数据的处理中心。</p>    <p>客户端所有组件都是在 action 中完成对流入数据的处理(如异步请求等),然后通过 action 触发 mutation 修改 state ,后由 state 经过 getter 分发给各组件,满足“单项数据流”的特点,同时也符合官方推荐的做法:</p>    <p><img src="https://simg.open-open.com/show/1eb567d0e0d34443f73fd2d8def3b737.png"></p>    <p>理解完最重要的 vuex 以后,其他部分也就顺利成章了。箭头表示数据的流动, LocalStorage 负责储存收藏夹的内容,方便下一次打开应用的时候内容不会丢失,node服务器负责根据关键字爬取搜狗API提供的数据。</p>    <p>是不是很简单?下面让我们一起来开始coding吧!</p>    <h2>初始化项目</h2>    <p>npm install vue-cli -g 安装最新版的 vue-cli ,然后 vue init webpack wechat-subscriptor ,按提示经过一步步设置并安装完依赖包以后,进入项目的目录并稍作改动,最终目录结构如下:</p>    <p><img src="https://simg.open-open.com/show/4ab2360436b6cb459bb3321b5330e575.jpg"></p>    <p>具体的内容请直接浏览 <a href="/misc/goto?guid=4959674919148929829" rel="nofollow,noindex">项目</a></p>    <h2>服务器&爬虫</h2>    <p>进入 /backend-server 文件夹并新建名为 crawler-server.js 的文件,代码如下:</p>    <pre>  <code class="language-javascript">/*** 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': '*'})      letkeyWord = encodeURI(url.parse(req.url, true).query.query)      // recieve keyword from the client side and use it to make requests      if (keyWord) {          letresultArr = []          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                  letresultObj = {                      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!')  </code></pre>    <p>一个简单的爬虫,通过客户端提供的关键词向搜狗发送请求,后利用 cheerio 分析获取关键的信息。这里贴上搜狗公众号搜索的地址,你可以亲自试一试: <a href="/misc/goto?guid=4959674919245041833" rel="nofollow,noindex">http://weixin.sogou.com/</a></p>    <p>当开启服务器以后,只要带上参数请求 localhost:8090 即可获取内容。</p>    <h2>使用 Vuex 作状态管理</h2>    <p>先贴上 vuex 官方文档: <a href="/misc/goto?guid=4959674919336639637" rel="nofollow,noindex">http://vuex.vuejs.org/en/index.html</a> ,相信我,不要看中文版的,不然你会踩坑,英文版足够了。</p>    <p>从前文的架构图可以知道,所有的数据流通都是通过 vuex 进行,通过上面的文档了解了有关 vuex 的用法以后,我们进入 /vuex 文件夹来构建核心的 store.js 代码:</p>    <pre>  <code class="language-javascript">/*** store.js ***/     importVuefrom 'vue'  importVuexfrom '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)    }  }     exportdefault new Vuex.Store({    state,    mutations  })  </code></pre>    <p>下面我们将对当中的代码重点分析。</p>    <p>首先我们定义了一个 state 对象,里面的两个属性对应着收藏夹内容,搜索结果。换句话说,整个APP的数据就是存放在 state 对象里,随取随用。</p>    <p>接着,我们再定义一个 mutations 对象。我们可以把 mutations 理解为“用于改变 state 状态的一系列方法”。在 vuex 的概念里, state 仅能通过 mutation 修改,这样的好处是能够更直观清晰地集中管理应用的状态,而不是把数据扔得到处都是。</p>    <p>通过代码不难看出,三个 mutation 的作用分别是:</p>    <ul>     <li>SET_RESULT :把搜索结果存入 state</li>     <li>COLLECT_IT :添加到收藏夹操作(包括 localstorage )</li>     <li>DELETE_IT :从收藏夹移除操作(包括 localstorage )</li>    </ul>    <h2>组件数据处理</h2>    <p>我们的APP一共有两个组件, SearchBar.vue 和 SearchResult.vue ,分别对应着搜索部分组件和结果部分组件。其中搜索部分组件包含着收藏夹部分,所以也可以理解为有三个部分。</p>    <p>搜索部分组件 SearchBar.vue</p>    <pre>  <code class="language-javascript">/*** 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))        })      }    }  }  </code></pre>    <p>代码有点长,这里仅重点介绍 vuex 部分,完整代码可以参考 <a href="/misc/goto?guid=4959674919148929829" rel="nofollow,noindex">项目</a> 。</p>    <ul>     <li>getters 获取 store 当中的数据作予组件使用</li>     <li>actions 的两个方法负责把数据分发到 store 中供 mutation 使用</li>    </ul>    <p>看官方的例子,在组件中向 action 传参似乎很复杂,其实完全可以通过 methods 来处理参数,在触发 actions 的同时把参数传进去。</p>    <p>结果部分组件 SearchResult.vue</p>    <pre>  <code class="language-javascript">/*** 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(letitemofcollectArr) {          if(item == name) return false        }        dispatch('COLLECT_IT', name)      }    }  }  </code></pre>    <p>结果部分主要在于展示,需要触发 action 的地方仅仅是添加到收藏夹这一操作。需要注意的地方是应当避免重复添加,所以使用了 for...of 循环,当数组中已有当前元素的时候就不再添加了。</p>    <h2>尾声</h2>    <p>关键的逻辑部分代码分析完毕,这个APP也就这么一回事儿,UI部分就不细说了,看看项目源码或者你自己DIY就可以。至于打包成APP,首先你要下载HBuilder,然后通过它直接打包就可以了,配套使用 mui 能够体验更好的效果,不知道为什么那么多人黑它。</p>    <p>搜狗提供的API很强大,但是提醒一下,千万不要操作太过频繁,不然你的IP会被它封掉,我的已经被封了……</p>    <p>Weex 已经出来了,通过它可以构建Native应用,想想也是激动啊,待心血来潮就把本文的项目做成 Weex 版本的玩玩……</p>    <p>最后的最后,感谢你的阅读,如果觉得我的文章不错,欢迎关注我的专栏,下次见!</p>    <p> </p>    <p><a href="/misc/goto?guid=4959675347701921552">阅读原文</a></p>    <p> </p>