Day66 Vue component-based development

 Introduction 1. json

   JSON (JavaScript Object Notation, JS object tag) is a lightweight data interchange format. 
It is based on a subset of ECMAScript (w3c js established specification), a fully independent programming language format to store text and presentation data.
Simple and clear hierarchy make JSON an ideal data-interchange language. Easy to read and write, but also easy for machines to parse and generate, and effectively improve the efficiency of network transmission.
Speaking of json objects must mention JS:

 

  

Qualified json objects:

["one", "two", "three"]

{ "one": 1, "two": 2, "three": 3 }

{"names": ["张三", "李四"] }

[ { "name": "张三"}, {"name":"John Doe"}] 
Copy the code

 

Failed json objects:

Name {: " Joe Smith " , ' Age ' : 32} // property name must use double quotes 

[ 32, 64, 128, 0xFFF] // not use a hexadecimal value of 

{ " name " : " Joe Smith " , " Age " :} // undefined not use undefined 

{ " name " : " Joe Smith " ,
   " Birthday " : a Date new new ( ' Fri, 26 is-Aug 2011 07:13:10 GMT ' ),
   "getName": Function () { return this.name;} // can not use the functions and objects date 
}  
copy the code

stringify and parse method

JSON.parse (): JSON string used to convert a JavaScript object 
EG: 
the console.log (the JSON.parse ( '{ "name": "Yuan"}' )); 
the console.log (the JSON.parse ( ' name {: "Yuan"} '));    // error 
the console.log (the JSON.parse (' [12 is, undefined] '));    // error 



JSON.stringify (): JavaScript value for the character into a JSON string. 
EG: the console.log (the JSON.stringify ({ 'name': "Egon"}));

 

 

2. js json data conversion method provided in <! DOCTYPE html>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>js提供的json数据转换方法</title>
</head>
<body>
<script>// json语法
    let emp = {
        "username": "xiaohu",
        "password": "1234567",
        "age": 20,
        'three': undefined,
        'five': function () {
            return 'test'
        }
    };
    console.log(emp);
    console.log(typeof emp);//JSON object provides conversion to json format data//
    
  
the stringify (json object) for converting # json string into
effect: the object into a JSON string, so ignore the attribute value does not meet JSON fields
the let Result = the JSON.stringify (EMP); the console.log (Result) ; the console.log ( typeof Result); // the parse (json string type data) is converted into the string for # json objects let json_str = '{ "password" : "1123", "age": 20, " name ":" xiaobai "} ' ; the console.log (json_str); the console.log ( typeof json_str); the let json_obj = the JSON.parse (json_str); the console.log (json_obj); the console.log ( typeof json_obj); Console .log (json_obj.age) </ Script> </ body> </html>

 3. ajax Introduction

   js ajax place allows the browser to send an http request to the backend application, the backend communication with the data and the operation information in a case where the user does not know, in order to achieve the partial refresh the page data / update the data without refreshing.

  ajax is a common technique used for data back-end interface operations provided by the front and rear ends in order to achieve separation site.

  The package has become a jQuery ajax function $ .ajax (), we can use this function to execute ajax requests directly.

  

jQuery version:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
</head>
<body>
<button id="btn">点击获取数据</button>
<script>
    $("#btn").click(function(){
        $.ajax({
            // 后端程序的url地址
            url: 'http://wthrcdn.etouch.cn/weather_mini',
            // 也可以使用method,提交数据的方式,默认是'GET',常用的还有'POST'
            type: 'get',
            dataType: 'json',  // 返回的数据格式,常用的有是'json','html',"jsonp"
            data:{ // 设置发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
                "city":'深圳'
            }
        })
        .done(function(resp) {     // 请求成功以后的操作
            console.log(resp);
        })
        .fail(function(error) {    // 请求失败以后的操作
            console.log(error);
        });
    });
</script>
</body>

注意点就是: 1.调用的是人家的接口 2.发送的数据类型是json 访问的url是接口, 3.回调函数的写法。

 

     .done(function(resp) {     // 请求成功以后的操作
            console.log(resp);
        })
        .fail(function(error) {    // 请求失败以后的操作
            console.log(error);
        });

 

vue.js默认没有提供ajax功能的。

 所以使用vue的时候,一般都会使用axios的插件来实现ajax与后端服务器的数据交互。

 注意,axios本质上就是javascript的ajax封装,所以会被同源策略限制。

axios 提供发送请求的常用方法有2个 axios.get() 和 axios.post()

  • 发送get请求
  • / 参数1: 必填,字符串,请求的数据接口的url地址,例如请求地址:http://www.baidu.com?id=200
        // 参数2:可选,json对象,要提供给数据接口的参数
        // 参数3:可选,json对象,请求头信息
 axios.get('服务器的资源地址',{ // http://www.baidu.com
        params:{
            参数名:'参数值', // id: 200,
        }
    
    }).then(function (response) { // 请求成功以后的回调函数
            console.log("请求成功");
            console.log(response.data); // 获取服务端提供的数据
    
    }).catch(function (error) {   // 请求失败以后的回调函数
            console.log("请求失败");
            console.log(error.response);  // 获取错误信息
    });
  • 发送POST请求
  •  // 发送post请求,参数和使用和axios.get()一样。
        // 参数1: 必填,字符串,请求的数据接口的url地址
        // 参数2:必填,json对象,要提供给数据接口的参数,如果没有参数,则必须使用{}
        // 参数3:可选,json对象,请求头信息

 

axios.post('服务器的资源地址',{
        username: 'xiaoming',
        password: '123456'
    },{
        responseData:"json",
    })
    .then(function (response) { // 请求成功以后的回调函数
      console.log(response);
    })
    .catch(function (error) {   // 请求失败以后的回调函数
      console.log(error);
    });

Vue版本获取天气信息:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
</head>
<body>
<div id="app">
    <button id="btn" @click="get_weather">点击获取天气</button>
    <p>{{weather_info}}</p>
</div>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            weather_info: {},
        },
        methods: {
            get_weather(){
                // 获取天气接口
                // axios.get("http://wthrcdn.etouch.cn/weather_mini?city=深圳"
                axios.get("http://wthrcdn.etouch.cn/weather_mini", {
                    // get请求的附带参数
                    params: {
                        "city": "深圳",
                    }
                }).then(response=>{
                    console.log(response.data);  // 获取接口数据
                    this.weather_info = response.data;
                }).catch(error=>{
                    console.log(error.response);  // 获取错误信息
                })
            }
        }
    })
</script>
</body>
</html>

 

运行结果:

 

 小结: 

1.请求成功的写法和请求失败的写法是写在一起的 通过关键字then catch 连接。

  axios.get("http://wthrcdn.etouch.cn/weather_mini", {
                    // get请求的附带参数
                    params: {
                        "city": "深圳",
                    }
                }).then(response=>{
                    console.log(response.data);  // 获取接口数据
                    this.weather_info = response.data;
                }).catch(error=>{
                    console.log(error.response);  // 获取错误信息
                })

 

 

 3. 同源策略

     同源策略,是浏览器为了保护用户信息安全的一种安全机制。所谓的同源就是指代通信的两个地址(例如服务端接口地址与浏览器客户端页面地址)之间比较,协议、域名(IP)和端口是否相同。不同源的客户端脚本[javascript]在没有明确授权的情况下,没有权限读写对方信息。

  ajax本质上还是javascript,是运行在浏览器中的脚本语言,所以会被受到浏览器的同源策略所限制。

  • 同源策略针对ajax的拦截,代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
</head>
<body>
<div id="app">
    <button id="btn" @click="get_music">搜索音乐</button>
</div>
<script>
    var vm = new Vue({
        el: "#app",
        data: {

        },
        methods: {
            get_music(){
                axios.get("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=叶问宗师"
                ).then(response=>{
                    console.log(response.data);
                }).catch(error=>{
                    alert("出错了!");
                    console.log(error.response);
                })
            }
        }
    })
</script>
</body>
</html>

 

 

  上面错误,关键词:Access-Control-Allow-Origin

  只要出现这个关键词,就是访问受限。出现同源策略的拦截问题。

 3.1 ajax跨域(跨源)方案之CORS 在返回的请求头中就行设置 从而限制

  ajax跨域(跨源)方案:后端授权[CORS],jsonp,服务端代理

 CORS是一个W3C标准,全称是"跨域资源共享",它允许浏览器向跨源的后端服务器发出ajax请求,从而克服了AJAX只能同源使用的限制。

 实现CORS主要依靠后端服务器中响应数据中设置响应头信息返回的。

比如在Django中的视图中就行设置:

 

# django的视图

def post(request):

​    response = Response()

​    response .set_header("Access-Control-Allow-Origin","http://localhost:63342")

​    return response

 

 

// 在响应行信息里面设置以下内容:
Access-Control-Allow-Origin: ajax所在的域名地址

Access-Control-Allow-Origin: www.oldboy.cn  # 表示只允许www.oldboy.cn域名的客户端的ajax跨域访问

// * 表示任意源,表示允许任意源下的客户端的ajax都可以访问当前服务端信息
Access-Control-Allow-Origin: *

 

 

 

  • jsonp我们通过代码了解一下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <p>严格来说:jsonp不是ajax技术,采用了script标签的加载跨域脚本的方式避开了同源策略</p>
    <p>jsonp技术的实现,是依靠服务端和浏览器端双方配合的</p>
    <p>api地址:https://suggest.taobao.com/sug?code=utf-8&q=商品名称&callback=cb</p>
    <button id="btn">点击搜索</button>

    <script>
        function hello(data) {
            console.log(data);
            alert(data.result);
        }

        let btn = document.getElementById("btn");
        btn.onclick = function () {
            // 1. 创建一个script标签
            script = document.createElement("script");
            // 2. 把script的src属性,设置为后端api的接口地址,而且后端接口返回的数据必须是js代码,
            // 这个代码中,必须调用一个客户端已经提前声明的函数。
            script.src = "https://suggest.taobao.com/sug?code=utf-8&q=咏春&callback=hello";
            document.head.appendChild(script);
        }
    </script>
</body>
</html>
  •  服务器端代理(运维帮忙设置)

总结:

1.同源策略 浏览器的一种保护用户数据的一种安全的机制。
浏览器会限制ajax不能跨源就行访问其他源的地址。
同源: 判断2个通信地址之间是否协议 域名IP 端口一直。

ajax:  ajax:  http://127.0.0.1/index.html
   api数据接口:  http://localhost/index

 这两个是同源么?不是同源的。是否同源的判断依据不会根据电脑来判断,而是通过协议、域名、端口的字符串是否来判断。

2. ajax默认情况下 会接收到同源策略的影响 一旦受到影响会报错如下:
  No 'Access-Control-Allow-Origin' header is present on the requested resource
3. 解决ajax只能同源访问数据接口的方式:
 1.CoRS 跨域资源共享 在服务器端的响应行中设置
Access-Control-Allow-Origin: 允许访问的域名地址
2.jsonp
3.是否 服务端代理
思路: 通过python来请求对应的服务器接口 获取到数据以后

 

 

二. 组件化开发

   组件 (component)是自定义封装的功能。在前端开发的过程中 进场出现多个网页的功能是重复的而且很多不同的页面之间,也存在同样的功能。

  把一个功能相关的HTML css JavaScript代码分装在一起组成一个整体代码的块的封装模式 我们称之为组件。

1.默认组件

写法步骤:

  * 组件名称:不要大写,也不要和原生的HTML标签同名,更不要任意使用特殊的符号
    * Vue.component("组件名称", {
    *     template: "html代码",  // 组件的HTML结构代码
    *     data(){
    *         return {}
    *     },
    *     methods: {  // 组件的相关的js方法
    *         方法名(){
    *             // 逻辑代码
    *         }
    *     }
    * }
  // `` 是js的多行字符串
    // 组件里面的data的值,必须是一个匿名函数,函数的返回值必须是一个json对象

 

  

 定义一个组件:

   

    Vue.component('myheader', {
        template: `<div>头部组件的HTML代码<h2 @click="demo" :class="className">{{message}}</h2></div>`,
        data(){
            return {
                "message": "hello, 我是组件里面的data数据",
                "className": "title"
            }
        },
        methods: {
            demo(){
                alert('你好!')
            }
        }
    });

    var vm = new Vue({
        el: "#app",
        data: {

        }
    })

 

 实例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>默认组件</title>
    <script src="js/vue.js"></script>
    <style>
        .title{
            color: blue;
        }

    </style>
</head>
<body>

<!--定义一个组件-->

<div id="app">
    <myheader></myheader>
</div>
<script>
    Vue.component('myheader', {
        template:  `<div>头部组件的html代码<h2 @click="demo" :class="className">{{message}}</h2></div>`,
        data(){
            return {
                "message": "hello, 我是组价里面的data数据",
                "className": "title"
            }
        },
        methods: {
            demo(){
                alert('你好!')
            }
        }
    });
    var vm = new Vue({
        el: "#app",
        data: {

        }
    })

</script>


</body>
</html>

 

 具体效果参考陈涛博客!

 三. Vue自动化工具(Vue-cli)

  前面学习了普通组件以后,接下来我们继续学习单文件组件则需要提前先安装准备一些组件开发工具。否则无法使用和学习单文件组件。

 

一般情况下,单文件组件,我们运行在 自动化工具vue-CLI中,可以帮我们编译单文件组件。所以我们需要在系统中先搭建vue-CLI工具,

  官网:https://cli.vuejs.org/zh/

  Vue CLI 需要 Node.js 8.9 或更高版本 (推荐 8.11.0+)。你可以使用 nvm 或 nvm-windows在同一台电脑中管理多个 Node 版本。

  nvm工具的下载和安装: https://www.jianshu.com/p/d0e0935b150a

             https://www.jianshu.com/p/622ad36ee020

 

 1. 安装node.js
Node.js是一个新的后端(后台)语言,它的语法和JavaScript类似,所以可以说它是属于前端的后端语言,后端语言和前端语言的区别:

运行环境:后端语言一般运行在服务器端,前端语言运行在客户端的浏览器上

功能:后端语言可以操作文件,可以读写数据库,前端语言不能操作文件,不能读写数据库。

  我们一般安装LTS(长线支持版本 Long-Time Support):

  下载地址:https://nodejs.org/en/download/【上面已经安装了nvm,那么这里不用手动安装了】

   node.js的版本有两大分支:

  官方发布的node.js版本:0.xx.xx 这种版本号就是官方发布的版本

  社区发布的node.js版本:xx.xx.x 就是社区开发的版本

   Node.js如果安装成功,可以查看Node.js的版本,在终端输入如下命令:

 

2. npm

 在安装node.js完成后,在node.js中会同时帮我们安装一个npm包管理器npm。我们可以借助npm命令来安装node.js的包。这个工具相当于python的pip管理器。

 

 

npm install -g 包名              # 安装模块   -g表示全局安装,如果没有-g,则表示在当前项目安装
npm list                        # 查看当前目录下已安装的node包
npm view 包名 engines            # 查看包所依赖的Node的版本 
npm outdated                    # 检查包是否已经过时,命令会列出所有已过时的包
npm update 包名                  # 更新node包
npm uninstall 包名               # 卸载node包
npm 命令 -h                      # 查看指定命令的帮助文档
 3. 安装Vue-cli
npm install -g vue-cli
 4. 使用Vue-cli初始化创建前端项目

 

 使用vue自动化工具可以快速搭建单页应用项目目录。

  该工具为现代化的前端开发工作流提供了开箱即用的构建配置。只需几分钟即可创建并启动一个带热重载、保存时静态检查以及可用于生产环境的构建配置的项目。

  生成一个基于 webpack 模板的新项目:

 

 

vue init webpack 项目目录名

例如:
vue init webpack com

 

 然后启动vue项目

cd com   # 切换到项目目录下
npm run dev   # 启动node提供的测试http服务器

 

运行了上面代码以后,终端下会出现以下效果提示

浏览器访问:http://localhost:8080

 5. 项目目录结构
 src:主开发目录,要开发的单文件组件全部在这个目录下的components目录下

  static:静态资源目录,所有的css,js文件放在这个文件夹

  dist:项目打包发布文件夹,最后要上线单文件项目文件都在这个文件夹中[后面打包项目,让项目中的vue组件经过编译变成js 代码以后,dist就出现了]

  node_modules:目录是node的包目录,

  config:是配置目录,

  build:是项目打包时依赖的目录

  src/router:路由,后面需要我们在使用Router路由的时候,自己声明.

 

 

 

整个项目是一个主文件index.html,index.html中会引入src文件夹中的main.js,main.js中会导入顶级单文件组件App.vue,App.vue中会通过组件嵌套或者路由来引用components文件夹中的其他单文件组件。

 

Guess you like

Origin www.cnblogs.com/longerandergou/p/11272618.html