Recent days project on-line, work relatively busy, no time more bo, fortunately today a little time and colleagues asked me a question, just a piece of solution
Using Vue to write a project is bound to encounter a problem, how to simulate the server to request data, then it will need to use node. js .
First, initialize and create a project
Vue Init webpack-simple Node-demo
CD Node-demo
NPM I
CNPM I Vuex axios-s
Second, write the interface
In the webpack.dev.conf.js file under the build file, add
"express" is based on the node. JS Backend Framework, responsible for routing, business logic, database operations, page and data response.
That is, the business layer in the architecture, responds to the request of the front-end, needs the database to pull the database content, needs to judge the processing return processing result, requests the page file return HTML file
const Express = require ( ' Express ') //through node access to analog data const app = Express (); //use Express framework to start a server //1. Read file var appData = require ( ". /data.json ') var seller = Appdata.sellervar goods = Appdata.goodsvar ratings = Appdata.ratings//2. Using Express To configure the route, specify an excuse to request var apiroutes = Express. Router () //define a route //expose API interface App. Use ( '/api ', apiroutes)
Add the devserver in the webpack.dev.conf.js file under the build file
// 添加接口数据 before(app){ // 配置请求路由和响应 app.get(‘/api/seller‘, (req, res) => { res.json({ errno: 0, //错误码 data: seller }) }) app.get(‘/api/goods‘, (req, res) => { res.json({ errno: 0, //错误码 data: goods }) }) app.get(‘/api/ratings‘, (req, res) => { res.json({ errno: 0, //错误码 data: ratings }) }) }
Such as:
Third, the use
AxiosRequest data
It's good to request data directly from the component.
<Template><Divclass="Seller" ><H1>{{seller}}</h1> </div> </template>< script>import axios from ' Axios ' export default {data () {return {seller:< Span class= "Hljs-string" '}}, mounted () {//request address Axios.get (/ Api/seller '). Then (resp = { This.seller = resp.data.data.name})}}</SCRIPT>
no--12 node. js
for impersonating server-side requests