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');
原文地址:https://www.cnblogs.com/huanghongzheng/p/11342727.html