一、Vue项目目录介绍
myfirstvue # 项目名字
node_modules # 文件夹,内部有很多当前项目依赖的模块,可以删除,npm install
public # 文件夹
-favicon.ico # 网站小图标
-index.html # spa:单页面应用
src # 以后咱们写代码,都在这下面
-assets # 静态资源,js,css,图片 类似于static文件夹
logo.png # 静态资源的图片
-components # 组件:小组件,用在别的大(页面组件)组件中
-HelloWorld.vue # 默认了一个hello world组件
-router # 装了vue-router自动生成的,如果不装就没有
index.js # vue-router的配置
-store # 装了vuex自动生成的,如果不装就没有
index.js # vuex的配置
-views # 放了一堆组件,页面组件
AboutView.vue # 关于 页面组件
HomeView.vue # 主页 页面组件
-App.vue # 根组件
-main.js # 整个项目启动入口
.gitignore # git的忽略文件
babel.config.js # babel的配置
jsconfig.json
package.json # 重要:类似于python项目的requirements.txt 当前项目所有依赖
package-lock.json # 锁定文件:package.json中写了依赖的版本,这个文件锁定所有版本
README.md # 项目的介绍
vue.config.js # vue项目的配置文件
二、es6导入导出语法
# 如果要导入,必须先导出
-默认导出
-命名导出
# 默认导出写法
1 写一个js ,在js中定义变量,函数,最后使用export defalut 导出
export default {
name: '彭于晏',
printName () {
console.log(this.name)
}
}
2 在想使用的js中,导入
import 随便起 from './lqz/utils'
#命名导出和导入
1 写一个js ,在js中定义变量,函数,最后使用export 导出
export const name = '刘亦菲'
export const printName = () => {
console.log('星象衔新宠')
}
2 在想使用的js中,导入
import {printName} from './lqz/utils'
# 在包下可以建立一个名为index.js 的文件,以后导入的时候,会默认找它
-对比python中得__init__.py
三、Vue项目开发规范
# 以后写的组件,都是单页面组件 使用 xx.vue 以后写一个组件就是一个xx.vue,页面组件和小组件
# 以后一个组件就是一个xx.vue,内部都有三部分
-<template></template> # html内容写在里面
-<script></script> # 写js内容
-<style></style> # 写css样式
# main.js 是整个入口
1 把App.vue根组件导入了,
2 使用new Vue({render: h => h(App)}).$mount('#app') 把App.vue组件中得数据和模板,插入到了index.html的id为app div中了
3 以后,只要在每个组件的export default {} 写之前学过的所有js的东西
4 以后,只要在每个组件的template,写模板,插值语法,指令。。
5 以后,只要在每个组件的style,写样式
四、Vue项目前后端结合
# 安装axios
npm install axios --S
# 导入使用
import axios from 'axios'
# 发送请求,获取数据
axios.get('http://127.0.0.1:8000/books/').then(res => {
console.log(res.data)
this.bookList=res.data
})
# 先用这种方式解决跨域(django 项目)
1 pip3 install django-cors-headers
2 app中注册:
INSTALLED_APPS = (
...
'corsheaders',
...
)
3 中间件注册
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
4 把下面的复制到配置文件中
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
五、前后端交互版登录功能
前端代码
models.py
from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.CharField(max_length=32)
publish = models.CharField(max_length=32)
views.py
from django.shortcuts import render
# Create your views here.
from rest_framework.viewsets import ModelViewSet
from .models import Book
from .serializer import BookModelSerializer
from django.http import JsonResponse
class BookView(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookModelSerializer
import json
def login(request):
username = json.loads(request.body).get('username')
password = json.loads(request.body).get('password')
if username == 'jason' and str(password) == '123':
return JsonResponse({'status': 100, 'msg': '登录成功'})
else:
return JsonResponse({'status': 101, 'msg': '用户名或密码错误'})
urls.py
from django.contrib import admin
from django.urls import path
from rest_framework.routers import SimpleRouter
from app01 import views
router = SimpleRouter()
router.register('books', views.BookView, 'books')
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', views.login),
]
urlpatterns += router.urls
serializer.py
from .models import Book
from rest_framework.serializers import ModelSerializer
class BookModelSerializer(ModelSerializer):
class Meta:
model = Book
fields = '__all__'
后端代码
App.vue
<template>
<div id="app" class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 class="text-center">登录功能</h1>
<div class="form-group">
<label for="">用户名:</label>
<input type="text" v-model="username" class="form-control">
<label for="">密码:</label>
<input type="text" v-model="password" class="form-control">
<br>
<button class="btn btn-danger" @click="handlerLogin">登录</button>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'App',
data() {
return {
bookList: [],
username: '',
password: '',
}
},
methods: {
handlerLogin() {
axios.post('http://127.0.0.1:8000/user/', {
username: this.username,
password: this.password,
}).then(res => {
console.log(res.data)
if (res.data.status == 100) {
location.href = 'http://www.baidu.com'
} else {
this.msg = res.data.msg
}
})
}
},
created() {
axios.get('http://127.0.0.1:8000/books/').then(res => {
console.log(res.data)
this.bookList = res.data
})
}
}
</script>
五、props配置项
# 接受父传子自定义的属性
-1 数组写法
-2 对象对象写法
-3 对象套对象写法
# 写法总结
// 普通使用
// props: ['msg'],
//属性验证
// props: {msg: String},
// 指定类型,必填和默认值
props: {
msg: {
type: String, //类型
required: true, //必要性
default: '老王' //默认值
}
},
六、混入
# mixin(混入) 可以把多个组件共用的配置提取成一个混入对象
把多个组件中公用的东西,抽取出来,以后可以全局使用和局部使用
# 使用步骤
-1 写个mixin/index.js
export const hunhe = {
data() {
return {
name: '彭于晏'
}
},
methods: {
handlePrintName() {
alert(this.name)
}
},
}
-2 局部导入:在组件中
import {hunhe} from "@/mixin";
mixins:[hunhe,]
-3 全局使用,在main.js 中 以后所有组件都可以用
import {hunhe} from "@/mixin";
Vue.mixin(hunhe)
七、插件
# 功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
# 使用步骤
-写一个 plugins/index.js
import Vue from "vue";
import axios from "axios";
import {hunhe} from '@/mixin'
export default {
install(miVue) {
// console.log(miVue)
// 1 vue 实例上放个变量
// Vue.prototype.$name = 'lqz' // 类比python,在类上放了一个属性,所有对象都能取到
// Vue.prototype.$ajax = axios
// 2 使用插件,加入混入
// 全局使用混入
// Vue.mixin(hunhe)
// 3 定义全局组件
// 4 定义自定义指令 v-lqz
Vue.directive("fbind", {
//指令与元素成功绑定时(一上来)
bind(element, binding) {
element.value = binding.value;
},
//指令所在元素被插入页面时
inserted(element, binding) {
element.focus();
},
//指令所在的模板被重新解析时
update(element, binding) {
element.value = binding.value;
},
});
}
}
2 在main.js 中使用插件
import plugins from '@/plugins'
Vue.use(plugins) // 本质使用use,会自动触发插件对象中得install
3 以后再组件中可以直接用插件中写的东西
八、scoped样式
# 在styple上写 <style scoped> </style>,以后只针对于当前组件生效
九、localstorage和sessionstorage
# window浏览器对象有的东西
# 如果想在浏览器中存储数据
永久存储:localStorage
关闭页面数据就没了(临时存储):sessionStorage
设定一个时间,到时候就过期:cookie
# 补充:序列化和反序列化
// 对象转json字符串
// JSON.stringify(person)
// json字符串转对象
// JSON.parse()
<template>
<div id="app">
<h1>localStorage操作</h1>
<button @click="saveStorage">点我向localStorage放数据</button>
<button @click="getStorage">点我获取localStorage数据</button>
<button @click="removeStorage">点我删除localStorage数据</button>
<h1>sessionStorage操作</h1>
<button @click="saveSessionStorage">点我向sessionStorage放数据</button>
<button @click="getSessionStorage">点我获取sessionStorage数据</button>
<button @click="removeSessionStorage">点我删除sessionStorage数据</button>
<h1>cookie操作</h1>
<button @click="saveCookie">点我向cookie放数据</button>
<button @click="getCookie">点我获取cookie数据</button>
<button @click="removeCookie">点我删除cookie数据</button>
</div>
</template>
<script>
import cookies from 'vue-cookies'
export default {
name: 'App',
data() {
return {}
},
methods: {
saveStorage() {
var person = {
name: '彭于晏',
age: 38
}
localStorage.setItem('userinfo', JSON.stringify(person))
},
getStorage() {
let userinfo = localStorage.getItem('userinfo')
console.log(userinfo)
console.log(typeof userinfo)
},
removeStorage() {
// localStorage.clear()
localStorage.removeItem('userinfo')
},
saveSessionStorage() {
var person = {
name: '彭于晏',
age: 38
}
sessionStorage.setItem('userinfo', JSON.stringify(person))
},
getSessionStorage() {
let userinfo = sessionStorage.getItem('userinfo')
console.log(userinfo)
console.log(typeof userinfo)
},
removeSessionStorage() {
// localStorage.clear()
sessionStorage.removeItem('userinfo')
},
saveCookie() {
cookies.set('name','lqz','7d') // 按秒计
},
getCookie() {
console.log(cookies.get('name'))
},
removeCookie() {
cookies.remove('name')
}
}
}
</script>
<style scoped>
h1 {
background-color: aqua;
}
</style>
十、集成elementui
# 第三方样式库,常见的有:
1.饿了么团队:elementui
2.iview
3.移动端的ui:vant
# 使用步骤
1.安装:
npm i element-ui -S
2.在main.js中引入
标签:10,Vue,name,31,js,vue,组件,import
From: https://www.cnblogs.com/dy12138/p/16845939.html