作者归档:Rick

webpack vue-cli 构建的项目(一)

注意node npm版本

"node": ">= 4.0.0",
"npm": ">= 3.0.0"
  • 执行以下命令
# 全局安装 vue-cli
$ npm install -g vue-cli
# 创建一个基于 "webpack" 模板的新项目
$ vue init webpack my-project
# 安装依赖,走你
$ cd my-project
$ npm install
  • 在开发过程中,使用命令
$ npm run dev

访问http://localhost:8080/

  • 生产环境打包
    打包之前,修改config/index.js文件

http://xhope.top/wp-content/uploads/2016/11/11.png

$ npm run build

双击dist/index.html

第一个React程序

开发程序示例

  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>let const变量</title>
</head>
<body>
    <div id="example"></div>


    <script src="http://cdn.bootcss.com/react/15.3.2/react.min.js"></script>
    <script src="http://cdn.bootcss.com/react/15.3.2/react-dom.js"></script>

    <script src="browser.min.js"></script>

    <script type="text/babel" src="src/test.js"></script>
</body>
</html>

一共用了三个库: react.jsreact-dom.jsBrowser.js,它们必须首先加载。其中,react.js 是 React 的核心库,react-dom.js是提供与 DOM 相关的功能,Browser.js的作用是将 JSX 语法转为 JavaScript 语法,这一步很消耗时间,实际上线的时候,应该将它放到服务器完成。

  • test.js
//JSX语法
ReactDOM.render(
 <h1>Hello, China!</h1>, 
 document.getElementById('example')
); 

//es6语法,纯测试打包
let input = [];
input.map(item => item + 1); 

在服务器环境下运行:http://localhost:8080/react/a.html,会打印Hello, China!

babel人肉打包

  • 省略安装babel安装命令
  • .babelrc
    注意此文件要在命令行创建:否则有可能创建不成功,命令touch .babelrc
{
    "presets": [
      "es2015",
      "react"
    ],
    "plugins": []
  }

执行命令:

$ babel src --out-dir build

这个时候在build目录下回出现test.js,babel把ES6与JSX同时编译。编译后的效果如下:

'use strict';

//JSX语法
ReactDOM.render(React.createElement(
  'h1',
  null,
  'Hello, China!'
), document.getElementById('example'));

//es6语法
var input = [];
input.map(function (item) {
  return item + 1;
});

调用页面index.html,type属性由原来的type/babel => type/javascript才能正确加载编译后的test.js

<script type="text/javascript" src="build/test.js"></script>

项目目录结构:
Alt text

参考文档

http://www.ruanyifeng.com/blog/2016/01/babel.html

http://www.07net01.com/2016/05/1499081.html

http://www.tuicool.com/articles/v6rQfye

http://reactjs.cn/react/docs/getting-started.html

http://www.css88.com/archives/5632#more-5632

http://www.ruanyifeng.com/blog/2015/03/react.html

https://segmentfault.com/a/1190000004170151

跨域问题–服务器配置(二)

跨域问题–JSONP(一)中使用的是JSONP的hack方式去解决跨越调用的问题。更常规的方式是通过服务器配置。
下面通过配置apache解决跨越问题,nginx的可以根据查询相关资料

修改配置文件httpd.conf
去掉注释LoadModule headers_module modules/mod_headers.so
在节点Directory中添加:

Header set Access-Control-Allow-Origin "*"

remote2.php

<?php
    $a = $_GET['a'];
    $b = $_GET['b'];
    $c = $a + $b;

    echo '{"result":"'.$c.'"}'; //从前台获取a和b,将a+b结果返回到回调函数
?>

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSONP</title>
</head>
<body>
   <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

   <script>
       $.getJSON("http://localhost:8080/remote2.php?a=2&b=9", function(data) {//像调用本地后台方法一样
            alert(data.result);
       })
   </script>
</body>
</html>

跨域问题–JSONP实现(一)

json.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSONP</title>
</head>
<body>
    <script>
        var localHandler = function(data){
             alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
        };
    </script>
    <script src="http://localhost:8080/remote.php?a=7&b=2&cb=localHandler"></script>
</body>
</html>

remote.php

<?php
    $a = $_GET['a'];
    $b = $_GET['b'];
    $c = $a + $b;
    $cb = $_GET['cb'];

    echo "$cb({result: $c})"; //从前台获取a和b,将a+b结果返回到回调函数
?>

启动apache,在浏览器访问:http://localhost:8080/remote.php?a=7&b=2&cb=localHandler
显示文本:

localHandler({result: 9})

跟期望的结果一致。
用浏览器打开在jsonp.html,会弹出对话框打印计算后结果。

jquery对jsonp的支持

后台php代码保持不变,js代码用jquery $.ajax代替

 <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

   <script>
        $.ajax({
             type: "get",
             async: false,
             url: "http://localhost:8080/remote.php?a=7&b=1",
             dataType: "jsonp",
             jsonp: "cb",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
             jsonpCallback:"localHandler",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
             success: function(data){
                 alert('我是本地函数,可以被跨域的remote.js文件调用,远程js带来的数据是:' + data.result);
             },
             error: function(){
                 alert('fail');
             }
         });
   </script>

jsonp不是ajax的一个特例,哪怕jquery等巨头把jsonp封装进了ajax,也不能改变着一点!
参考链接:
http://harttle.com/2015/10/10/cross-origin.html
https://segmentfault.com/a/1190000003710973

vue一个简单应用

最近在学习vue,做的一个小的例子程序。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>留言板</title>
    <link href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            margin-top: 20px;
        }

        .user-list {
            margin-top: 20px;
            border-top: 1px solid #ccc;
        }

        .user-list h2 {
            text-align: center;
        }

        .user-list th,td {
            text-align: center;
        }

    </style>
</head>
<body>
    <div class="container" id="user-box">
        <form role="form" v-on:keyup.enter="addUser();">
              <div class="form-group">
                <label for="email">姓名</label>
                <input type="text" class="form-control" id="name" v-model="name" placeholder="请输入姓名">
              </div>
              <div class="form-group">
                <label for="age">年龄</label>
                <input type="number" class="form-control" id="age" v-model="age" placeholder="请输入年龄">
              </div>
              <button type="button" class="btn btn-primary" @click="addUser();">添加</button>
              <button type="button" class="btn btn-danger" v-on:click="reset();">重置</button>
        </form>

        <div class="user-list">
            <h2>用户信息表</h2>
            <table class="table table-bordered">
              <tr>
                  <th>序号</th>
                  <th>姓名</th>
                  <th>年龄</th>
                  <th>操作</th>
              </tr>
              <tr v-show="this.users.length == 0">
                  <td colspan="4">暂时没有用户数据</td>
              </tr>
              <tr v-for="(user, index) in users">
                 <td>{{index+1}}</td>
                 <td>{{user.name}}</td>
                 <td>{{user.age}}</td>
                 <td><button type="button" class="btn btn-danger" data-toggle="modal" data-target="#myModal"
                 v-on:click="nowIdx = index;dialogTitle = '确认删除用户【'+user.name+'】?';">删除</button></td>
              </tr>
              <tr v-show="this.users.length > 0">
                  <td colspan="4"><div class="pull-right"><button type="button" class="btn btn-danger" data-toggle="modal" 
                  data-target="#myModal" v-on:click="index = -1;dialogTitle = '确认删除全部用户?';">删除全部</button></div></td>
              </tr>
            </table>

        </div>

        <div class="modal fade" id="myModal">
              <div class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <h4 class="modal-title">{{dialogTitle}}</h4>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-danger" v-on:click="makeDel();">确定</button>
                  </div>
                </div><!-- /.modal-content -->
              </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    </div>


    <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
    <script src="http://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="http://cdn.bootcss.com/vue/2.0.3/vue.min.js"></script>


    <script src="demo.js"> </script>
</body>
</html>

demo.js

var users = JSON.parse(localStorage.getItem('u')|| "[]");

        new Vue({
            el: '#user-box',
            data: {
                users:  users,
                name: '',
                age: '',
                dialogTitle: '',
                nowIdx: -1
            },
            methods: {
                addUser: function() {
                    this.users.push({"name": this.name, "age": this.age});

                    localStorage.setItem('u', JSON.stringify(this.users));

                    this.reset();
                },
                reset: function() {
                    this.name = '';
                    this.age = '';
                },
                makeDel: function() {
                     if (-1 === this.nowIdx) {
                        this.users = [];
                    } else {
                         this.users.splice(this.nowIdx,1);
                    }
                    $('#myModal').modal('toggle');
                    localStorage.setItem('u', JSON.stringify(this.users));
                }
            }
        });

null