Html
1.基本标签
<h1>最大的标题</h1>
<h2> . . . </h2>
<h3> . . . </h3>
<h4> . . . </h4>
<h5> . . . </h5>
<h6>最小的标题</h6><p>这是一个段落。</p>
<br> (换行)
<hr> (水平线)
<!-- 这是注释 -->
2.文本格式化
<b>粗体文本</b>
<code>计算机代码</code>
<em>强调文本</em>
<i>斜体文本</i>
<kbd>键盘输入</kbd>
<pre>预格式化文本</pre>
<small>更小的文本</small>
<strong>重要的文本</strong><abbr> (缩写)
<address> (联系信息)
<bdo> (文字方向)
<blockquote> (从另一个源引用的部分)
<cite> (工作的名称)
<del> (删除的文本)
<ins> (插入的文本)
<sub> (下标文本)
<sup> (上标文本)
3.链接
普通的链接:<a href="http://www.example.com/">链接文本</a>
图像链接: <a href="http://www.example.com/"><img decoding="async" src="URL" alt="替换文本"></a>
邮件链接: <a href="mailto:webmaster@example.com">发送e-mail</a>
书签:
<a id="tips">提示部分</a>
<a href="#tips">跳到提示部分</a>
4.图片
<img decoding="async" loading="lazy" src="URL" alt="替换文本" height="42" width="42">
5.无序列表
<ul><li>项目</li><li>项目</li>
</ul>
6.有序列表
<ol><li>第一项</li><li>第二项</li>
</ol>
7.表格
<table border="1"><tr><th>表格标题</th><th>表格标题</th></tr><tr><td>表格数据</td><td>表格数据</td></tr>
</table>
8.表单
<form action="demo_form.php" method="post/get">
<input type="text" name="email" size="40" maxlength="50">
<input type="password">
<input type="checkbox" checked="checked">
<input type="radio" checked="checked">
<input type="submit" value="Send">
<input type="reset">
<input type="hidden">
<select>
<option>苹果</option>
<option selected="selected">香蕉</option>
<option>樱桃</option>
</select>
<textarea name="comment" rows="60" cols="20"></textarea></form>
Css
1.选择器
/*id选择器*/
#p {text-align:center;color:black;font-family:arial;
}
/*class选择器*/
.center {text-align:center;}
2.文本和字体
h1 {text-align:center;}
p.date {text-align:right;}h1 {font-size:40px;}
3.链接
a:link {color:#000000;} /* 未访问链接*/
a:visited {color:#00FF00;} /* 已访问链接 */
a:hover {color:#FF00FF;} /* 鼠标移动到链接上 */
a:active {color:#0000FF;} /* 鼠标点击时 */
4.隐藏
h1.hidden {display:none;}
5.定位position
p.pos_fixed
{position:fixed; /* 元素的位置相对于浏览器窗口是固定位置 */position:relative; /* 相对定位元素的定位是相对其正常位置 */position:absolute; /*绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于<html>*/
}
6.浮动
/*使元素向左或向右移动,其周围的元素也会重新排列*/
img
{float:right;
}
7.对齐
margin: auto;
text-align: center;
/*依据实际情况还可以使用position: absolute,margin,padding,float 实现*/
8.图像
img
{opacity:0.4; /* 透明度 */
}
img:hover /* 悬停 */
{opacity:1.0;
}
JavaScript
1.输出
window.alert("") //弹出警告框。
document.write("") //方法将内容写到 HTML 文档中。
document.getElementById("demo").innerHTML = "段落已修改。" //写入到 HTML 元素。
console.log("") //写入到浏览器的控制台
2.函数
function myFunction(a,b){// var定义的变量可以修改,如果不初始化会输出undefined,不会报错var obj = {name:"Fiat", model:500, color:"white"};//const定义的变量不可以修改,而且必须初始化。const s = "s";return a*b;
}
3.常用事件
onchange //HTML 元素改变
onclick //用户点击 HTML 元素
onmouseover //鼠标指针移动到指定的元素上时发生
onmouseout //用户从一个 HTML 元素上移开鼠标时发生
onkeydown //用户按下键盘按键
onload //浏览器已完成页面的加载
4.DOM
var x=document.getElementById("intro");
var y=x.getElementsByTagName("p");
var x=document.getElementsByClassName("intro");
5.改变Html
document.getElementById("p1").innerHTML="新文本!"; // 改变html
document.getElementById(id).attribute="新属性值"; // 改变属性
document.getElementById(id).style.property="新样式" // 改变CSS
6.DOM 元素 (节点)
尾部创建新的 HTML 元素 (节点) - appendChild()
头部创建新的 HTML 元素 (节点) - insertBefore()
移除HTML 元素 - removeChild()
替换 HTML 元素 - replaceChild()
var para = document.createElement("p");
var node = document.createTextNode("这是一个新的段落。");
para.appendChild(node);var element = document.getElementById("div1");
element.appendChild(para);
7.字符串
str.match("world");
str.replace("Microsoft","Runoob");
8.弹框
alert("你好,我是一个警告框!"); // 警告框
var r=confirm("按下按钮");
if (r==true){}else{} // 确认框
var person=prompt("请输入你的名字","Harry Potter");
if (person!=null && person!=""){} // 提示框
Vue
创建Vue工程
模板语法
文本插值,原始 HTML,Attribute 绑定,动态参数
<template><p>{{ msg + '!' }}</p><div v-html="vhtml"></div><div :id="bindId"></div><button :disabled="isButtonDisabled">Button</button><div v-bind="objectOfAttrs"></div><button @click="clk()">按钮</button><hr><a :[attr]="123">动态参数</a>
</template><script setup>
import { ref } from 'vue';const msg = ref("hello world");
const vhtml = '<span style="color: red">This should be red.</span>';
const bindId = "divid";
const isButtonDisabled = true;
const attr = 'href';
const objectOfAttrs = {id: 'divid',class: 'wrapper'
}
function clk(){msg.value='clik !';
}
</script>
<style>
#divid{background: blue;width: 100px;height: 100px;
}
.wrapper{margin: 50px;
}
</style>
响应式基础
<template><p>{{ reactiveMsg.msg + '!' }}</p><p>{{ refMsg }}</p><button @click="clk()">按钮</button>
</template><script setup>
import { reactive, ref } from 'vue';// ref用于普通类型,使用需要.value;reactive用于复杂类型(对象类型),使用不需要.value
// 建议优先使用ref,reactive某些情况会失去响应,参考https://blog.csdn.net/m0_57033755/article/details/129043116
const reactiveMsg = reactive({'msg':'hello world'});
const refMsg = ref('123');
function clk(){reactiveMsg.msg='clik !';refMsg.value = 'clik!';
}
</script>
计算属性
<template><p>{{ msg }}</p><p>{{ reverseMsg }}</p>
</template><script setup>
// 计算属性,相比于method有缓存
const msg = 'hello world';
const reverseMsg = computed(()=>{return msg.split('').reverse().join('');
})
</script>
侦听器
<template><p>{{ msg }}</p><input type="text" v-model="msg"><p>{{ obj.age }}</p><button @click="obj.age = 11">改变msg</button>
</template><script setup>
import { ref, watch, reactive } from "vue";const msg = ref('hello world');
const obj = reactive({ count: 0,age: 1,name:'qwe' })
// watch监听器,当某一个值改变时进入
watch(msg, (newValue, oldValue) => {console.log(oldValue);console.log(newValue);
})
// 加上immediate代表初始化也会进入
watch(msg, (newValue, oldValue) => {console.log(oldValue);console.log(newValue);
}, { immediate: true })
// 监听对象时,自动为深度监听,监听每一个属性变化,影响性能
watch(obj, (newValue, oldValue)=>{console.log(newValue);
})
// 监听对象某一个属性
watch(() => obj.age, (newValue, oldValue) => {console.log(newValue);
})
</script>
Class 与 Style 绑定
<template><p :class="{font : true}">hello</p><!-- 推荐使用驼峰命名 --><p :style="{color : 'red', fontSize : '50px'}">hello!!!</p>
</template><script setup>
</script><style>
.font{font-size: large;color: blue;
}
</style>
条件渲染
<template><p v-if="type == 'A'">A</p><p v-else-if="type == 'B'">B</p><p v-else >C</p><input type="text" v-model="type"><!-- 因为v-if是一个指令,他必须依附于某个元素。如果我们想要切换不止一个元素 <template> 元素上使用 v-if,这只是一个不可见的包装器元素,最后渲染的结果并不会包含这个 <template> 元素 --><template v-if="true"><p>111</p><p>111</p><p>111</p></template><p v-show="true">hello!!!</p>
</template><script setup>
import { ref } from "vue";const type = ref('A')
</script>
列表渲染
<template><ul><li v-for="person in persons" :key="person">{{ person }}</li></ul><button @click="addItem()">增加元素</button><ul><li v-for="(person,index) in persons" :key="index">{{ person }} -> {{ index }}</li></ul><ul><li v-for="obj in objs" :key="obj.name">{{ obj.name }} : {{ obj.age }}</li></ul>
</template><script setup>
import { reactive } from "vue";const persons = reactive(['aaa','bbb','ccc']);
const objs = [{'name':'qqq','age':1},{'name':'www','age':2}]
function addItem(){// 数组变化// push() 末尾添加// pop() 末尾删除// shift() 首位删除// unshift() 首位添加// splice() 删除,插入,替换// sort() 排序// reverse() 反转persons.push('ddd');
}
</script>
事件处理
<template>
{{ count }}
<button @click="count++">add 1</button>
<button @click="addNum(10)">add 10</button>
<!-- 只传递event对象时,方法不要加上() -->
<button @click="eventClik">event</button>
<button @click="eventClik2(5, $event)">event2</button>
<!--多事件处理-->
<button @click="addNum(1), addNum(2)">多事件处理+3</button>
</template><script setup>
import { ref } from "vue";const count = ref(0);
function addNum(num){count.value += num;
}
function eventClik(event){alert('hello ' + count.value)console.log(event);
}
function eventClik2(num, event){count.value += num;console.log(event);
}
</script>
事件修饰符
<template><div @click="divClick"><!-- stop:阻止事件冒泡 --><button @click.stop="btnClick">按钮</button></div><div><form action=""><!-- prevent:阻止默认行为 --><input type="submit" value="提交" @click.prevent="submitClick"></form><!-- once:只触发一次 --><button @click.once="btnClick">点击一次</button><div><!-- keyup.enter:键盘事件,enter回弹时触发 --><input type="text" @keyup.enter="keyUp"></div></div>
</template><script setup>
function divClick(){alert('父元素');
}
function btnClick(){alert('子元素')
}
function submitClick(){alert('提交成功');
}
function keyUp(){alert('回车确定');
}
</script>
表单输入绑定
<template><p>文本:{{ textMessage }}</p><input type="text" v-model="textMessage"><div><!-- 单个复选框,v-model绑定boolean,代表是否勾选 --><input type="checkbox" v-model="checked">{{ checked }}</div><div><p>选取角色:{{ users }}</p><!-- 多个复选框,需要设置value,v-model绑定value --><input type="checkbox" id="tom" value="Tom" v-model="users"><!-- label可以用来配合input的id,和直接使用字符串没区别 --><label for="tom">Tom</label><input type="checkbox" id="rose" value="Rose" v-model="users">Rose<input type="checkbox" id="jerry" value="Jerry" v-model="users">Jerry</div><div><p>pick: {{ picked }}</p><!-- 单选按钮,需要设置value否则返回on,v-model绑定value,可以省略name --><input type="radio" id="one" value="One" v-model="picked">One<input type="radio" id="two" value="Two" v-model="picked">Two</div><div><p>选择:{{ english }}</p><!-- 选择器单选,value可以省略 --><select v-model="english"><option>A</option><option>B</option><option>C</option></select></div><div><p>选择水果:{{ fruits }}</p><!-- 选择器多选,value可以省略 --><select v-model="fruits" multiple><option>苹果</option><option>香蕉</option><option>橘子</option></select></div>
</template><script setup>
import { ref } from "vue";const textMessage = ref('文本');
const checked = ref(false);
const picked = ref('');
const english = ref('A');
const users = ref([]);
const fruits = ref([]);
</script>
v-model修饰符
.lazy 懒加载,失去焦点再更新
.number 输出变为数字类型
.trim 去除两端空格
父子组件相互传值
父组件:
<template><!-- 使用组件,传递参数;此处:msg父传子;@parentValue子传父 --><hello :msg="msg" @parentValue="getValue"></hello>
</template><script setup>
// 引入组件
import hello from './components/hello.vue';
const msg = 'app.vue';
// 子组件自定义事件对应方法
function getValue(value){alert(value);
}
</script>
子组件:
<template><div>hello</div>{{ msg }}<div><button @click="sendMsgToParent">监听事件传递子组件参数到父组件</button></div>
</template>
<script setup>
// 使用父组件传递的参数
defineProps(['msg']);
// 使用自定义组件实现子传父
const emit = defineEmits(['parentValue']);
function sendMsgToParent(){emit('parentValue', 'from son');
}
</script>
父子组件相互获取值
父组件:
<template><!-- ref可以用来获取该页面dom元素和子组件数据 --><hello ref="helloComponent"></hello><div ref="div"><span></span></div>
</template><script setup>
import hello from './components/hello2.vue';
import { onMounted, provide, readonly, ref } from 'vue';
// ref获取dom元素需要先定义
let helloComponent = ref(null);
const div = ref('');
onMounted(() => {console.log(helloComponent.value.msg);console.log(div.value);
})
// 子获取父数据需要用到provide/inject,setup语法糖只支持一次provide一个变量,readonly只读
provide('div', readonly(div));
</script>
子组件:
<template>{{ msg }}
</template>
<script setup>
import { inject, onMounted, ref } from 'vue';let msg = '子组件';
// 获取父组件provide的值
const div = inject('div');
// setup语法糖写法下组件是默认私有的,defineExpose就是setup语法糖写法中将特定属性、方法显式暴露的宏指令。
// 只有在子组件通过defineExpose显式暴露的属性、方法才能被父组件通过ref获取并使用。
// 需要注意defineExpose必须写在声明好的属性、方法之下,否则会报错!
defineExpose({msg
});
onMounted(() => {console.log(div.value);
})
</script>
插槽
父组件:
<template><hello><!-- 不取名字直接使用 --><span>123123</span><!-- 取名字的插槽需要template包裹 --><template v-slot:msg><h4>来自父组件的信息</h4></template><template v-slot:btn><button>按钮</button></template></hello>
</template><script setup>
import hello from './components/hello3.vue';
</script>
子组件:
<template><div><!-- 插槽相当于占位符 --><slot></slot><slot name="msg"></slot><slot name="btn"></slot></div>
</template>
路由
安装vue路由:
npm install vue-router@4
视图组件包含:
views/Home.vue
views/Error.vue
views/About.vue:
<template><h1>About</h1>
</template>
<script setup>
import { onMounted } from "vue";
import {useRoute} from 'vue-router'onMounted(() =>{alert(useRoute().params.id)
})
</script>
router/index.js:
import {createRouter, createWebHashHistory} from 'vue-router'
// 导入路由组件
import Home from '../views/Home.vue'
import About from '../views/About.vue'
// 404页面
import Error from '../views/Error.vue'
// 路由映射
const routes = [{path: '/',redirect: '/home'},{path: '/home',component: Home},// :id传参, 传参还可以使用props,接收端需要使用defineProps{path: '/about/:id', component: About},// 匹配所有路径{path: '/:path(.*)', component: Error}
]const router = createRouter({history: createWebHashHistory(),routes
})
// 导出,其他组件才能引入
export default router
main.js:
import router from './router'import { createApp } from 'vue'
import App from './App.vue'const app = createApp(App)
// router必须放在app前面
app.use(router)
app.mount('#app')
App.vue:
<template><div><h1>Hello App!</h1><!-- 底层为a标签 --><router-link to="/">Go to Home</router-link><div></div><router-link to="/about/123">Go to About</router-link><!-- 视图渲染在这里 --><router-view></router-view></div>
</template>
嵌套路由
views/Parent.vue:
<template><h1>Parent</h1><router-link to="/parent/children1">Go to Children1</router-link><div></div><router-link to="/parent/children2">Go to Children2</router-link><router-view></router-view>
</template>
index.js:
import { createRouter, createWebHashHistory } from 'vue-router'
// 导入路由组件
import Parent from '../views/Parent.vue'
import Children1 from '../views/Children1.vue'
import Children2 from '../views/Children2.vue'
// 路由映射
const routes = [{path: '/parent',component: Parent,children: [{path: 'children1',component: Children1},{path: 'children2',component: Children2}]}
]const router = createRouter({history: createWebHashHistory(),routes
})
// 导出,其他组件才能引入
export default router
使用js实现路由
<template><h1>Page</h1><button @click="pageClk">跳转按钮</button>
</template>
<script setup>
import {useRouter} from 'vue-router'// useRouter一定要放在setup方法内的顶层,否则作用域改变useRouter()执行返回的是undefined
const router = useRouter();
function pageClk(){// js方法实现路由跳转router.push('/parent');
}
</script>
命名视图
同时 (同级) 展示多个视图
views/Top.vue
views/Main.vue
views/Foot.vue
index.js:
import { createRouter, createWebHashHistory } from 'vue-router'
// 导入路由组件
import top from '../views/Top.vue'
import main from '../views/Main.vue'
import foot from '../views/Foot.vue'
// 路由映射
const routes = [{path: '/name',components: {default: main,top,foot}}
]const router = createRouter({history: createWebHashHistory(),routes
})
// 导出,其他组件才能引入
export default router
App.vue:
<template><div><h1>Hello App!</h1><router-link to="/name">Go to 命名视图</router-link><router-view name="top"></router-view><router-view></router-view><router-view name="foot"></router-view></div>
</template>
路由守卫
index.js:
常用来做路由间跳转的判断,规定用户或权限
router.beforeEach((to, from, next) => {if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })else next()
})
Proxy跨域
安装axios:
npm install axios
vite.config.js:
import { defineConfig } from 'vite'
export default defineConfig({server: {proxy: {'/path': {target: 'https://i.maoyan.com', // 替换地址changeOrigin: true, // 开启跨域rewrite: path => path.replace(/^\/path/, '') // 重写路径}}}
})
使用方:
<script setup>
import axios from 'axios';
// 访问域名 https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E6%88%90%E9%83%BD&ci=59&channelId=4
axios.get('/path/api/mmdb/movie/v3/list/hot.json?ct=%E6%88%90%E9%83%BD&ci=59&channelId=4').then((res) => {console.log(res);
})
</script>
axios和后端通信
<template><div>{{ data }}</div>
</template><script setup>
import axios from 'axios'
import { onMounted, ref } from 'vue';const data = ref('')onMounted(() => {// 考虑跨域axios.get('/local/page-helper/').then(function(res){//.then()表示成功的回调console.log(res.data) data.value = res.data})
})
</script>
Vue3状态管理
存储文件:
import { reactive } from "vue";export const store = reactive({count: 0,increment(){this.count++}
})
调用方:
<template><div><span>{{ store.count }}</span></div><button @click="store.increment">按钮</button>
</template><script setup>
import { store } from './store/index';
</script>
Pinia状态管理
安装Pinia:
npm install pinia
main.js:
import {createPinia} from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
store.js:
import {defineStore} from 'pinia'
import {ref, computed} from 'vue'// 按照规范返回值使用use***Store,defineStore第一个参数必须独一无二
export const useAgeStore = defineStore('ageStore', () => {const age = ref(0) // statefunction addAge(){ //actionsage.value ++}const getAge = computed(() => { // getterreturn age.value + 5})return { age, addAge, getAge}
})
使用:
<template><div>{{ ageStore.age }}{{ ageStore.getAge }}</div><button @click="ageStore.addAge">add</button>
</template><script setup>
import {useAgeStore} from './store/ageStore';const ageStore = useAgeStore()
</script>