vue的交互、過濾器和生命週期的簡單介紹

交互(vue中如何發送ajax)

前端和後端

        任何一個程序都會有前端和後端

        前端:客戶端-------》瀏覽器

        後端:服務器端------》硬件服務器 性能比較穩定的電腦

前端和後端交互的流程?

        前端------》ajax------》後端(接受請求)------》數據庫----》後端(返回數據)----》前端(展示數據)

 在vue中數據請求的方式有很多種  vue-resource  axios  fetch等(vue-resource是vue官方出得插件   axios第三方的  Fetch 是es6的)

vue-resource雖然是官方出的但是在2.0版本的時候已經停止更新了。

vue的核心包裏面沒有http請求。如果我們想完成數據請求的話,必須必須必須引用一些外部的文件。比如vue-resource  通過vue-resource可以幫助我們來進行數據請求。

下載:npm install --save vue-resource

vue-resource的get請求語法:

this.$http.get(

        "url":請求的地址,

        {params:{key:val,key:val}}  發送的數據

).then((res)=>{})

前端程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue-resource的get請求</title>
</head>
<body>
     <div id="app">
        <button @click="fun()">點我發送get請求</button>
     </div>
</body>
<script src="./node_modules/vue/dist/vue.min.js"></script>
<script src="./node_modules/vue-resource/dist/vue-resource.min.js"></script>
<script>
    const vm=new Vue({  
        el:'#app',
        data:{},
        methods: {
            fun(){
                this.$http.get(
                    "http://localhost:3000/vue/get",
                    {params:{name:"前端發送數據後臺接受數據"}}
                )
                .then((ok)=>{
                    console.log(ok);      
                })
            }
        },
    })
</script>
</html>

後端簡單程序

const express=require("express");
const app=express();
// 跨域
app.use('/',(req,res,next)=>{
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');   
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS');
    next()
})
app.get('/vue/get',(req,res)=>{
    // 後臺接受數據req.query.name
    console.log(req.query.name); 
    res.send({msg:"get數據請求成功"})
})
app.listen(3000)

 

 

vue-resource的post請求語法: 

this.$http.post(

        "url"   數據請求地址,

        {key:val,key:val}  你要發送的數據,

        {emulateJSON:true}  模擬json方式來進行數據的傳遞

}.then((ok)=>{}}

前端程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue-resource的post請求</title>
</head>
<body>
     <div id="app">
        <button @click="fun()">點我發送post請求</button>
     </div>
</body>
<script src="./node_modules/vue/dist/vue.min.js"></script>
<script src="./node_modules/vue-resource/dist/vue-resource.min.js"></script>
<script>
    const vm=new Vue({  
        el:'#app',
        data:{},
        methods: {
            fun(){
                this.$http.post(
                    "http://localhost:3000/vue/post",
                    {data:"post前端發送數據後臺接受數據"},
                    {emulateJSON:true}
                )
                .then((ok)=>{
                    console.log(ok);      
                })
            }
        },
    })
</script>
</html>

後端簡單程序

const express=require("express");
const app=express();
// 應用body-parse模塊  接受前端數據
const bodyParser=require("body-parser")
// 解析模塊
const uE=bodyParser.urlencoded({extended:false})
// 跨域
app.use('/',(req,res,next)=>{
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');   
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS');
    next()
})
app.post('/vue/post',uE,(req,res)=>{
    // 接受數據req.body.data
    console.log(req.body.data);
    res.send({msg:"post的響應數據"})
})
app.listen(3000)

 

 axios(重要)

Axios 是一個第三方的數據請求插件,不僅可以在vue中使用  還能在其他的地方也都可以使用比如說react

 下載:npm install --save axios 

語法:

get請求:

axios({

    url:"請求地址",

    method:"get" , 請求方式

    params:{key:val,key:val}發送的數據

}).then((ok)=>{

    console.log(ok)

})

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <button @click="fun()">點擊get請求</button>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/axios/dist/axios.js"></script>
<script>
    const vm=new Vue({
        el:'#app',
        data:{},
        methods: {
            fun(){
                axios({
                    url:'http://localhost:3000/vue/get',
                    method:'get',
                    params:{name:"我是axios方式發送的get數據"}
                }).then((ok)=>{
                    console.log(ok);               
                })
            }
        },
    })
</script>
</html>

 後臺服務器程序同vue-resource的請求一樣

post請求

Axios({

    url:地址,

    method:”post”,

    data:{key:val,key:val}

}).then((ok)=>{

    console.log(ok)

})

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <button @click="fun()">點擊post請求</button>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/axios/dist/axios.js"></script>
<script>
    const vm=new Vue({
        el:'#app',
        data:{},
        methods: {
            fun(){
                const usp=new URLSearchParams();
                usp.append('data',"我是axios方式發送的post數據")
                axios({
                    url:'http://localhost:3000/vue/post',
                    method:'post',
                    // data:{data:"我是axios方式發送的post數據"}  //後臺接受爲undefined  用URLSearchParams處理post中的參數  使用append的方式進行插入  append("要發送數據的key","要發送數據的val")
                    data:usp
                }).then((ok)=>{
                    console.log(ok);               
                })
            }
        },
    })
</script>
</html>

 後臺服務器程序同vue-resource的請求一樣

練習  .使用axios完成真實api接口請求

 

過濾器

什麼是過濾器

在不改變數據的情況下  輸出我們想要的數據。

問題:請說一下vue中的內置過濾器

在使用vue的時候是2.0以後的版本,在2.0版本的時候就沒有內置過濾器了。如果想使用過濾器,需要自己定義過濾器。在早期1x版本的時候是有的,但是1x很少使用。

vue中如何自定義過濾器

1.全局過濾器

全局過濾器就是定義好之後,在頁面中所有的實例都可以使用。

語法:創建位置在vue實例之前

Vue.filter("定義過濾器的名字",(val)=>{

    return 過濾的邏輯

})

val:需要過濾的數據

使用過濾器:|  管道符

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>全局過濾器</title>
</head>
<body>
    <div id="app">
        <!-- 2.調用過濾器 | -->
        <h1>{{str | demo}}</h1>
    </div>
    <div id="app1">
        <!-- 2.調用過濾器 | -->
        <h1>{{text | demo}}</h1>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.min.js"></script>
<script>
    // 1.創建過濾器
    Vue.filter('demo',(val)=>{
        return val.substr(2,4)
    })
    const vm=new Vue({
        el:'#app',
        data:{
            str:"hgndgakuib"
        }
    })
    const vm1=new Vue({
        el:'#app1',
        data:{
            text:"客服我本辦法不方便發表回覆不會比"
        }
    })
</script>
</html>

2.局部過濾器

局部過濾器就是定義好之後,只能在當前實例中使用

語法:定義在vue實例中與el data methods wacth等這些屬性同級

filters:{

    定義過濾器的名字(val){

        return 過濾邏輯

    }

}

注意:過濾器在沒有衝突的情況下可以串聯使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>局部過濾器</title>
</head>
<body>
    <div id="app">
        <!-- 2.調用過濾器 | -->
        <h1>{{str | demo | add}}</h1>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.min.js"></script>
<script>
    const vm=new Vue({
        el:'#app',
        data:{
            str:"hgndgakuib"
        },
        // 1. 創建局部過濾器
        filters:{
            demo(val){
                return val.substr(3,6)
            },
            add(val){
                return val.toUpperCase()
            }
        }
    })
</script>
</html>

 實例的生命週期

生命週期:實例在創建到銷燬經過的一系列過程叫做實例的生命週期

 在生命週期中被自動執行的執行的函數=>鉤子函數/生命週期鉤子

生命週期鉤子函數的用途

在生命週期的特定階段會被自動調用,爲我們開發者提供了一個自己執行的邏輯的機會

步驟

1.實例創建

    beforeCreat(實例創建開始) el data還沒掛載

    created(實例創建結束)數據和視圖已經綁定了  data的數據改變了,那麼視圖有會隨之發生改變

2.模板創建

    beforeMount

    mounted

3.更新過程

    beforeUpdate開始更新

    updated

4.銷燬過程

    beforeDestroy開始銷燬

    destroyed

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>實例的生命週期</title>
</head>
<body>
    <!-- 
        1.vue頁面第一次加載的時候會觸發幾個鉤子
            4個鉤子  beforeCreat  created beforeMount  mounted 
        2.vue生命週期的作用
            在生命週期的特定階段會被自動調用,爲開發者提供一個自己執行的邏輯機會
        3.vue的生命週期一共幾個階段
            4個階段 
            1.實例創建  beforeCreat  created
            2.模板創建  beforeMount  mounted
            3.更新過程  beforeUpdate updated
            4.銷燬階段  beforeDestroy destroyed
        4.DOM渲染在那個生命週期中完成
            mounted
        5.請您描述vue的生命週期 ---》8個鉤子對應的意思
        6.設置數據請求的時候是在哪個鉤子
            created:由於在當前鉤子裏面dom並沒有渲染 所以在當前鉤子裏面進行數據請求的時候 不要進行dom操作
            mounted:dom已經被渲染完畢了 如果要進行dom操作的時候
     -->
    <div id="app">{{text}}
        <button @click="text='實例修改了'">點擊更新</button>
        <button @click="del()">點我進行銷燬操作</button>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.min.js"></script>
<script>
    const vm=new Vue({
        el:'#app',
        data:{
            text:"這是一個實例",
        },
        methods:{
            del(){
                // 執行的是vue的銷燬操作
                this.$destroy()
            }
        },
        beforeCreate(){
            // $el 過去頁面中關聯的DOM元素
            console.log("實例開始初始化,開始配置數據觀測 屬性 方法,後掛載還沒開始  $el裏面還沒東西");      
        },
        created(){
            console.log("實例創建完成  已經配置好了數據觀測 屬性 方法,$el沒有東西");       
        },
        beforeMount(){
            // render()渲染方法吧內容進行頁面的渲染
            console.log("在掛載之前被調用,相關的render被首次調用");  
        },
        mounted(){
            console.log("$el已經有內容");     
        },
        beforeUpdate(){
            console.log("準備數據更新");       
        },
        updated(){
            console.log("頁面的內容已經更新完成");    
        },
        beforeDestroy(){
            console.log("實例銷燬之前調用,實例還可以正常使用");    
        },
        destroyed(){
            console.log("實例銷燬之後被調用,vue實例會把所有內容解除綁定");
            
        }
    })
</script>
</html>

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章