es6之导入导出-模块化,登录跳转电影网页案例,scoped,elementui

Ⅰ es6之导入导出-模块化

【一】默认导出和导入

-默认导出和导入
    	-导出:export default {name,add}
        -导入:import 别名 from '../xx/'
        -组件的导入和注册
        	-导出组件对象--->当前组件中注册成局部组件-->当前组件中使用
  • 代码实现
# utils.js中导出   这是自定义的一个文件夹 下的js文件
const NAME='zyb'
function add(a,b){
    return a+b
}
// 默认导出对象 : 只能导出一个
export default {NAME,add,demo(){
        console.log('demo')
    }}


#  其他js中导入
// 默认导出后,导入语法--》
// import 后写别名  from 后写路径
import hjb from './zzz/utils'
let res=hjb.add(2,3)
console.log(res)
console.log(hjb.NAME)
hjb.demo()



# 如果在一个文件夹下-->js文件名叫 index.js-->只导入到文件这一层
import hjb from './zzz'   # index.js  是首页  所以只要有  只导入到文件夹这一层就会自动到 index.js

【二】命名导入导出

    -命名导出和导入
    	-导出: 
        	export const name='hjj'
            export const add=()=>{}
            export function demo(){}
            export const aaa=demo
       -导入
    	import {name,add} from '路径'
        import {name as name1,add} from '路径'
        import * as 对象 from '路径'
  • 代码实现
# 导出   utils.js
// 命名导出
function mark(){
    console.log('mark')
}
export const name='hjj'
export const add=(a,b)=>a+b

function park(){
    console.log('普通函数')
    mark()  // 相当于py里面的封装
}
export const f=park


#  其他js中导入
//命名导出后,命名导入语法
import {name,f} from "./zzz/utils";  // 用谁导出谁
// import * as 对象 from "./zzz/utils";
// import {name as a,f} from "./zzz/utils";  //  重命名 name as a
console.log(name)
f()


# 导入路径
	-相对-->相对于导入文件当前
    -绝对-->import {name,f} from "@/package/utils"; -->@ 代指src
    
    
# 如果是在html的script标签中,要写type="module"
<script type="module">
    import jjj from './zzz'
    console.log(jjj.add(4,5))
    console.log(jjj.f(5))
</script>

Ⅱ 登录跳转电影网页案例

【一】后端(django)

	- 后端
    	- 跨域问题解决:按步骤操作
        - 登录接口:使用simple-jwt 返回格式定制
        - 查看电影信息接口
        	-ViewSet:自动生成路由+不需要序列化
            -方法名 :films--->打开文件读出来,使用Response返回即可
            -文件路径:以运行的py文件所在目录为根
        - 统一返回格式:comm_exception_handler

【1】解决跨域(第三方)

# 统一按如下方式解决跨域
	-1 安装
    	pip3 install django-cors-headers
    -2 app中注册
        INSTALLED_APPS = [
            。。。
            'corsheaders',
        ]
    -3 中间件中注册
        MIDDLEWARE = [

            'corsheaders.middleware.CorsMiddleware',
        ]
    -4 配置文件中配置
    # 允许跨域源
    CORS_ORIGIN_ALLOW_ALL = True
    # 允许的请求头
    CORS_ALLOW_HEADERS = (
        "accept",
        "accept-encoding",
        "authorization",
        "content-type",
        "dnt",
        "origin",
        "user-agent",
        "x-csrftoken",
        "x-requested-with",

        # 额外允许的请求头
        'token',
    )

【2】 后端逻辑分析

# 1 前端传入 用户名+密码-->后端接收到-->认证auth的user表,通过后签发token
# 2 不需要写登录了,只需要使用simple-jwt-->定制返回格式即可
# 3 写个返回电影数据

【3】登录

# 1 路由
from django.urls import path
from rest_framework_simplejwt.views import token_obtain_pair
urlpatterns = [
    path('login/', token_obtain_pair),
]
# 2 定制返回格式  serializer.py
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        old_data = super().validate(attrs)
        data = {'code': 100,
                'msg': '登录成功成功',
                'token': old_data.get('access'),
                }
        return data

# 2.1 在settings.py配置文件
SIMPLE_JWT = {
  "TOKEN_OBTAIN_SERIALIZER": "app01.serializer.MyTokenObtainPairSerializer",
}
    
    
    
# 3 统一异常处理 exceptions.py
from rest_framework.views import exception_handler
from rest_framework.response import Response
def common_exception_handler(exc, context):
    res=exception_handler(exc, context)
    if res:
        response=Response({'code':999,'msg':res.data.get('detail')})
    else:
        response = Response({'code': 888, 'msg':'登录失败'})
    return response


# 3.1 配置文件

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'app01.exceptions.common_exception_handler',
}


INSTALLED_APPS = [
    'rest_framework',
    'rest_framework_simplejwt',
]


LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False

【4】电影

# 路由
from django.contrib import admin
from django.urls import path
from rest_framework.routers import SimpleRouter
from app01.views import FilmView
router=SimpleRouter()
router.register('films',FilmView,'films')
from rest_framework_simplejwt.views import token_obtain_pair
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', token_obtain_pair),
]
urlpatterns+=router.urls
# 视图类
from django.shortcuts import render

# Create your views here.
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
import json

from rest_framework.decorators import action

import os
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'film.json')

class FilmView(ViewSet):
    @action(methods=['GET'], detail=False)
    def films(self, request):
        with open(file_path,'r',encoding='utf-8') as f:
            res_dict = json.load(f)
        return Response(res_dict)

【二】前端(vue)

- 前端
    	 安装axios:nodejs环境中 cnpm i axios -S
         使用:导入使用
        	import axios from 'axios'
            axios.post(地址,{username:this.username,password:this.password}).then( 			         response=>{
                response.data
             }).catch(error=>{})
         路由跳转
        	this.$router.push('/films')
         新建页面组件,注册路由
        
         显示电影:created中发送ajax请求

【1】路由

import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'
import FilmView from '../views/FilmView.vue'



Vue.use(VueRouter)

const routes = [

     {
        path: '/login',
        name: 'login',
        component: LoginView
    },
     {
        path: '/films',
        name: 'films',
        component: FilmView
    },
 
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

【2】登录页面

<template>
<div>
  <p>用户名:<input type="text" v-model="username"></p>
  <p>密码:<input type="password" v-model="password"></p>
  <p><button @click="handleLogin">登录</button></p>
</div>
</template>

<script>
import axios from "axios";

export default {
  name: "LoginView",
  data(){
    return {
      username:'',
      password:''
    }
  },
  methods:{
    handleLogin(){
      // 发送ajax请求到后端-->post请求
      axios.post('http://127.0.0.1:8000/login/',{
        username:this.username,
        password:this.password
      }).then(res=>{
        if(res.data.code==100){
          //跳转到电影页面
          this.$router.push('/films')
          // 保存token到浏览器中
        }else {
          alert(res.data.msg)
        }
      }).catch(err=>{
        alert(err)
      })

    }
  }
}
</script>

<style scoped>

</style>

【3】电影页面

<template>
  <div>
    <h1>最新电影</h1>
    <div v-for="item in film_list" :key="item">
      <h3>{{ item.name }}</h3>
      <p>{{ item.synopsis }}</p>
      <img :src="item.poster" alt="" height="400px" width="200px">

      <hr>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "FilmView",
  data() {
    return {
      film_list: []
    }

  },
  created() {
    axios.get('http://127.0.0.1:8000/films/films/',{
      headers:{
        Authorization:''
      }
    }).then(res => {
      this.film_list = res.data.results
    })
  }
}
</script>

<style scoped>

</style>

Ⅲ scoped

# 加在 style 标签上,表示当前style中得所有样式只对当前组件有效
<style scoped>
h1{
  color: aqua;
}
</style>   

Ⅳ elementui

# 1 开源的样式库,方便在vue中使用
	-elementui:饿了么团队开源的  web端
    	https://element.eleme.cn/#/zh-CN
    -vant:有赞团队,移动端,微信小程序
    	https://vant-ui.github.io/vant/v2/#/zh-CN/grid
    -ant design:阿里团队
    	https://1x.antdv.com/docs/vue/introduce-cn/
    -iView
    	https://v2.iviewui.com/components/grid
    -nutui:京东团队
    	https://nutui.jd.com/2x/#/dialog 移动端
        
# 2 项目中集成
	1 安装:cnpm install element-ui -S
    2 集成到项目:main.js 中加入
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    Vue.use(ElementUI); // 使用插件
    3 去官网,找样式,复制,粘贴

posted on 2024-08-15 02:02  silence^  阅读(2)  评论(0编辑  收藏  举报

导航