Vue項目入口與小知識總結


vue-route

name使用

路由配置
import Main from './views/Main'
routes: [
    {
        path: '/main',
        name: 'main',
        component: Main
    }
]
視圖使用
<router-link :to="{name: 'main'}">主頁</router-link>
router-link與系統a標簽的區別
router-link:會被vue渲染成a標簽,但是點擊這樣的a標簽不能發生頁面的轉跳,只會出現組件的替換
a:也可以完成同樣的效果,但是會發生頁面的轉跳
路由重定向
routes: [
	{
        path: '/',
        name: 'home',
        component: Home
    },
    {
        path: '/home',
        redirect: '/', // 重定向
    }
]

路由傳參-1

1、html通過:to="'/course/detail/' + course.id"拼接得到跳轉路由,來建立跳轉連接和在鏈接中攜帶參數
2、路由通過path: '/course/detail/:id', 路由方面通過:id來接收變化的參數
3、跳轉的新頁面通過路由接收參數,但參數的接收在頁面創建成功后,並同過鈎子函數created來獲取路由,在鈎子函數內通過this.$route.params拿到鏈接中的變量,然后通過.k的形式取到變量中的值

路由:router.js
{
    // path如果是通過to直接訪問,路由必須完全對應
    // :id代表可以完成任意內容匹配,用變量id保存 
    // 請求/course/detail/1 和 /course/detail/abc,id變量分別存的1和abc
    // path: '/course/detail/1',  // 死的
    path: '/course/detail/:id',  // 活的
    name: 'course-detail',
    component: CourseDetail
}
轉跳頁面:Course.vue
<template>
    <div class="course">
        <h1>課程</h1>
        <hr>

        <ul>
            <li v-for="course in courses" :key="course.title">
                <router-link :to="'/course/detail/' + course.id">{{ course.title }}</router-link>
            </li>
        </ul>

    </div>
</template>

<script>
    let course_list = [
        {
            id: 1,
            title: '水滸傳'
        },
        {
            id: 2,
            title: '西游記'
        },
        {
            id: 3,
            title: '金瓶'
        },
    ];
    export default {
        name: "Course",
        data () {
            return {
                courses: []
            }
        },
        // 組件創建成功去獲取數據
        created () {
            this.courses = course_list
        },


    }
</script>

<style scoped>
    li a {
        display: block;
    }
    li, li a {
        border: 1px solid pink;
        background-color: rgba(123, 21, 56, 0.3);
        margin-top: 10px;
        line-height: 80px;
        cursor: pointer;
    }
</style>
渲染頁面:CourseDetail.vue
<template>
    <div class="course-detail">
        <h1>課程詳情</h1>
        <hr>
        <h2>{{ ctx }}</h2>
    </div>
</template>

<script>
    let course_detail_list = [
        '數據有誤', '水滸傳', '西游記', '金瓶'
    ];

    export default {
        name: "CourseDetail",
        data () {
            return {
                ctx: ''
            }
        },
        created () {
            console.log('詳情頁面被渲染了');
            // this.$route:負責路由的數據
            // this.$router:負責路由的路徑
            // this.$route.params可以拿到鏈接中 :變量 變量中的數據
            let index = this.$route.params.id;
            if (index < 0 || index >= course_detail_list.length) index = 0;
            this.ctx = course_detail_list[index]
        }
    }
</script>

<style scoped>

</style>

路由傳參-2

1、html通過:to="'/course/detail?id=' + course.id"拼接新鏈接(url后加?的方法拼接)、
2、路由不變原樣路由方式傳遞並攜帶參數
3、跳轉的新頁面通過路由接收參數,最終通過鈎子函數中的this.$route.query來獲取鏈接

路由:router.js
{
    path: '/course/detail',
    name: 'course-detail',
    component: CourseDetail
}
轉跳頁面:Course.vue
<router-link :to="'/course/detail?id=' + course.id">{{ course.title }}</router-link>
渲染頁面:CourseDetail.vue
created () {
    let index = this.$route.query.id;
    if (index < 0 || index >= course_detail_list.length) index = 0;
    this.ctx = course_detail_list[index]
}

路由傳參-3

1、html頁面通過點擊事件來發送點擊事件中攜帶的參數 轉跳的方法 (參數)
2、點擊事件的方法中通過this.$router.push()傳送參數push中傳name或者path和params或者query加參數門
3、跳轉的新頁面通過let 參數的數據 = this.$route.query.參數的key 或者 this.$route.params.參數的key

路由:router.js
{
    path: '/course/detail',
    name: 'course-detail',
    component: CourseDetail
}
轉跳頁面:Course.vue
methods: {
    轉跳的方法 (參數) {
        this.$router.push({
            name: 'course-detail',
            params 或者 query: {
                參數們
            },
            : {
                參數們
            }
        })
    }
}
渲染頁面:CourseDetail.vue
created () {
    let 參數的數據 = this.$route.query.參數的key 或者 this.$route.params.參數的key
}

倉庫

1、通過點擊事件將數據提交存入到倉庫中

btnClick () {
      // alert(this.$store.state.title)
      // this.$store.state.title = 456;

      this.$store.commit('updateTitle', this.val);
      console.log(this.$store.state.title)
}

或者通過watch監聽變量的變化更新倉庫中的變量值

watch: {
            val () {
                 // this.$store.commit('updateTitle', this.val);
                 this.$store.state.title = this.val
            }
        }

2、通過全局變量mutations來更新倉庫中的數據

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex);

export default new Vuex.Store({
    // 全局可以訪問的變量 - 獲取值
    // 組件內:this.$store.state.title
    state: {
        title: '主頁'
    },
    // 全局可以訪問的方法 - 修改值
    // 組件內:this.$store.commit('updateTitle', '新值')
    mutations: {
        updateTitle (state, newValue) {
            state.title = newValue
        }
    },
    actions: {}
})

3、通過全局變量state來獲取倉庫中的數值this.$store.state.title,並通過computed監聽倉庫中的值的變化

computed: {
            title () {
                return this.$store.state.title
            }
        }

前后台數據交互axios

安裝

>: cd 項目目錄
>: cnpm install axios --save

配置:main.js

import Axios from 'axios'
Vue.prototype.$axios = Axios;

跨域問題(同源策略):Access-Control-Allow-Origin => CORS

前提:前台向后跳請求數據
1)服務器不一致 - ip
2)應用不一致 - 端口
3)協議不一致 - http <-> https

django解決跨域

'''
1)安裝django-cors-headers模塊

2)在settings.py中配置
# 注冊app
INSTALLED_APPS = [
	...
	'corsheaders'
]
3)添加中間件
MIDDLEWARE = [
	...
	'corsheaders.middleware.CorsMiddleware'
]
4)允許跨域源
CORS_ORIGIN_ALLOW_ALL = True
'''

axios請求方式

get

this.$axios({
    url: 'http://localhost:8000/test/data/',
    method: 'get',
    params: {
        usr: 'zero',
        pwd: '000'
    }
}).then((response) => {
    console.log(response.data)
}).error((error) => {
    console.log(error)
});


this.$axios.get('http://localhost:8000/test/data/', {
    params: {
        usr: 'zero',
        pwd: '000'
    }
}).then((response) => {
    console.log(response.data)
}).error((error) => {
    console.log(error)
});

post

#客戶端通過json發送的post數據被放到body中需要通過request.body獲取
#import json
#print('post:',json.loads(request.body.decode('utf-8')))

this.$axios({
    url: 'http://localhost:8000/test/data/',
    method: 'post',
    data: {
        username: 'owen',
        password: '123'
    }
}).then((response) => {
    console.log(response.data)
}).error((error) => {
    console.log(error)
});


this.$axios.post('http://localhost:8000/test/data/', {
    username: 'owen',
    password: '123',
    headers: {
        'Content-Type': 'urlencoded'
    }
}).then((response) => {
    console.log(response.data)
}).error((error) => {
    console.log(error)
});

安裝

>: cd 項目目錄
>: cnpm install vue-cookie --save

配置:main.js

import cookie from 'vue-cookie'
Vue.prototype.$cookie = cookie;

使用:在任何方法中

// token是后台返回的

// 設置cookie
// this.$cookie.set(key, value, time)
this.$cookie.set('token', token, 1);

// 取出cookie
// this.$cookie.get(key)
console.log(this.$cookie.get('token'));

// 刪除cookie
// this.$cookie.delete(key)
this.$cookie.delete('token');


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM