Vue.js(慕课网学习笔记一)

来源:互联网 发布:网络访问安全设计 编辑:程序博客网 时间:2024/05/15 00:22

使用vue开始一个项目

使用vue构建一个大型的项目 官方推荐使用NPM安装,NPM 能很好地和诸如 Webpack 或 Browserify 模块打包器配合使用。 Vue.js 也提供配套工具来开发单文件组件。
使用NPM很简单,只需下面的几步就可以开始一个普通的模板项目:

全局安装 vue-cli
npm install –global vue-cli

创建一个基于 webpack 模板的新项目 也可以是Browserify 只需把下面一行的webpack改掉即可
vue init webpack my-project

进入工程安装依赖
cd my-project
npm install

运行项目
npm run dev

模拟后台数据

1 找一个json文件放在项目的根目录下面。
2 去项目的 build=>dev-server.js文件中配置请求你路径
3 配置方法:

var appData = require('../data.json');var seller = appData.seller;var goods = appData.goods;var ratings = appData.ratings;var apiRoutes = express.Router();apiRoutes.get('/seller',function(req,res){res.json({    resCode : 0,    data : seller});});apiRoutes.get('/goods',function(req,res){res.json({    resCode : 0,    data : goods});});apiRoutes.get('/ratings',function(req,res){res.json({    resCode : 0,    data : ratings});});app.use('/api', apiRoutes);

配置完成之后执行npm run dev 重启服务在浏览器中输入http://localhost:8080/api/seller,http://localhost:8080/api/goods, http://localhost:8080/api/ratings就可以看到请求到的json数据了。

vue-router

项目中肯定会用到页面的跳转,使用vue-router可以很好的控制调节界面的跳转。
使用vue-router :

  1. 在package.json中的dependencies中添加vue-router的依赖 如”vue-router”: “^2.3.1”
  2. 在项目中router文件夹下面的index.xml中引入vue-router : import Router from ‘vue-router’ 并使用Vue.use(Router)
  3. 创建Router实例 在实例中配置各种路径。

网络请求

一个正式的项目基本都有跟后台数据交互,vue中目前官方推荐使用axios
使用方法:
npm install axios
在使用的类中引入 import axios from ‘axios’
get方法:

// Make a request for a user with a given IDaxios.get('/user?ID=12345')  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });// Optionally the request above could also be done asaxios.get('/user', {    params: {      ID: 12345    }  })  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });

post方法:

axios.post('/user', {    firstName: 'Fred',    lastName: 'Flintstone'  })  .then(function (response) {    console.log(response);  })  .catch(function (error) {    console.log(error);  });

执行多个并发请求

function getUserAccount() {  return axios.get('/user/12345');}function getUserPermissions() {  return axios.get('/user/12345/permissions');}axios.all([getUserAccount(), getUserPermissions()])  .then(axios.spread(function (acct, perms) {    // Both requests are now complete  }));