使用 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 :
网络请求
一个正式的项目基本都有跟后台数据交互,vue 中目前官方推荐使用 axios
使用方法:
npm install axios
在使用的类中引入 import axios from 'axios'
get 方法:
- // Make a request for a user with a given ID
- axios.get('/user?ID=12345')
- .then(function (response) {
- console.log(response);
- })
- .catch(function (error) {
- console.log(error);
- });
- // Optionally the request above could also be done as
- axios.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
- }));
来源: http://www.tuicool.com/articles/IZfaAvy