一、定义变量和应用类型(数组,对象)
常量用 ref() 引用类型用 reactive()
import {ref, reactive} from 'vue'
let num = ref(0)
let obj = reactive({
a:1,
b:2
})
let arr = reactive([1,2,3])
用ref获取dom
<input ref="refDom">
onMount(()=>{
refDom.value&&refDom.value.focus()
})
二、proxy
vue3 中的数据监听用的是new proxy() ,proxy 里面有三个方法,get set delete, 所以在更改对象属性时,也会监听到。
三、计算属性 使用
let componentsFn = computed({
return value
})
let componentsFn = computed({
get(){
return value
},
set(){
return value
}
})
四、watch的使用
分为两种 监听ref 定义的数据, 监听reactive定义的数据
let str = ref('abc')
warch(str,(newval,oldval)=>{
console.log(newval, oldval)
})
let obj = reactive({
a:1,
b: 2
})
watch(()=>obj.a,(new, old)=>{console.log(new, old)})
监听多个值 (new 和 old 分别是数组,对应前面所监听的)
watch([str,()=>obj.a],(new, old)=>{
console.log(new, old)
})
立即监听和深度监听
watch(
[str,()=>obj.a],
(new, old)=>{console.log(new, old},
{
immediate: true, //立即监听
deep: true //深度监听
})
watchEffect
1.watchEffect自动收集依赖数据,依赖数据更新时重新执行自身
2.立即执行,没有惰性,页面的首次加载就会执行
3.无法获取到原值,只能得到变化后的值
4.不用指明监视哪个属性,监视的回调中用到哪个属性就监视哪个属性
watchEffect(()=>{
fullname.value = user.firstname+ '' + user.lastname
})
五、 生命周期
vue2 vue3
beforeCreate setup
create setup
beforeMount onBeforeMount
mounted onMount
beforeUpdate onBeforeUpdate
updated onUpdate
beforeDestroy onBeforeUnMount
destroyed onUnmounted
onMount(()=>{
console.log('onMount')
})
六、自定义hooks
自定义hooks就类似组件一样只不过只封装js,当有一段js代码需要复用可以把他封装成一个hooks进行复用
需求,在别的页面插入一个hooks实现记录鼠标点击就的坐标
1.新建hooks 文件 里面定义一个usea.js 文件
export default function(){
let points = reactive({x: 0, y :0})
function myclick(event){
points.x=event.pageX
points.y=event.pageY
}
onMounted(()=>{
//点击的是窗口所以要给窗口定义点击事件
window.addEventListener("click",myclick)
})
return points
}
2.在使用hooks 的文件中引入
import usea from "../hooks/usea.js
let point = usea()
七、跨组件通信 (provide inject)
爷爷组件定义provide
provide:{
a: 123
}
子组件、孙组件中接收
inject:['grandpaMsg'],
script-setup 模式一共提供了 4 个宏—(仅限在script-setup 模式中使用)
宏只在编译的时候执行,运行时不执行,所以写顶部。编写时会把宏编译成运行时的代码。
defineProps:父传子
<div>
//父页面
<child :bar="Num"></child>
</div>
<script steup>
import child from './child.vue'
const num = ref(123)
</script>
子组件
<script steup>
const props = defineProps({bar:Number}) //跟vue2 props:{} 一样
console.log(props.bar)
</script>
defineEmits 子组件调用父页面方法
<div>
//父页面
<child @bar="bar"></child>
</div>
<script steup>
import child from './child.vue'
const bar= ()=>{
console.log(113)
}
</script>
子组件
<script steup>
const emit = defineEmits({(e:'bar',num:number)})
const clickFn = ()=>{
emit('bar',123)
}
</script>
defineExpose
向外暴露属性,被使用。
<div>
//父页面
<child @bar="bar" ref="childRef"></child>
</div>
<script steup>
import child from './child.vue'
import {ref} from 'vue'
consr childRef = ref()
onMounted(()=>{
console.log(childRef.value.isShow) // false
)
const bar= ()=>{
console.log(113)
}
</script>
子组件
<script steup>
import {ref} from 'vue'
const isShow = ref(false)
defineExpose({
isShow
})
</script>
withDefaults 设置 Vue 组件的默认属性值。它接受两个参数
const props = withDefaults(
defineProps<{
// 数据列表
lotteryList: { pic: string; name?: string }[];
// 中奖id
winId: number;
// 抽奖初始转动速度
initSpeed: number;
// 抽奖最快转动速度
fastSpeed: number;
// 抽奖最慢转动速度
slowSpeed: number;
// 基本圈数
baseCircles: number;
// 样式类名前缀
classPrefix: string;
}>(),
{
lotteryList: () => [],
// 中奖id
winId: 0,
// 抽奖转动速度
initSpeed: 300,
fastSpeed: 100,
slowSpeed: 600,
// 基本圈数
baseCircles: 4,
}
);
八、v-model 的本质
1.在input中使用没什么变化
2.在组件中使用
<sun v-model="a">
内部 本来是 :value @input
props: ['modelValue'] value改成modelValue
emit('update:modelValue', props.modeValue) 改成了 emit('update:modelValue', props.modeValue)
九、v-if 和 v-for
v-if 的优先级高于 v-for 以前是v-for 高于v-if
十、路由
useRoute 获取当前路由对象
useRouter 获取当前路由实例,可以进行路由跳转
const route = useRoute();
console.log(route)
const router = useRouter();
const goHome = ()=>{
router.push('/home')
}
十一、使用vuex
1. 下载 npm i vuex --save
2.新建store文件,在store里新建index.js 文件
3.在main.js中引入
import store from '../src/store'
app.use(store)
import { createStore } from 'vuex'
export default createStore({
state: {
count: 1,
name: '',
params: '',
},
getters: {
changeCount: (state)=>{
return state.count+4
},
},
mutations: {
changeName(state, name) {
state.name = name
},
asyncchange(state, params) {
state.params = params
}
},
actions: {
async changeParams({state, commit}, payload) {
function httpRole(data) {
console.log('请求参数===>', data) //模拟请求参数
return new Promise((resolve) => {
setTimeout(() => {
resolve(['admin', 'add'])
}, 300)
})
}
let resp = await httpRole({id: payload}) //模拟请求
commit('asyncchange', resp)
}
},
modules: {
}
})
3.在其他文件中使用
import { useStore } from 'vuex'
const {state,getters} = useStore();
console.log(state.count);
console.log(getters.changeCount);
const nameFn = ()=>{
commit('changeName','zs')
dispatch('changeParams', 999)
}