computed 计算属性
两种书写方式
- 函数类型
- 对象类型
函数类型
<template>
<input v-model="frist" type="text"> <br/>
<input v-model="last" type="text"> <br/>
<p>我的名字叫: {{name}}</p>
</template>
<script setup lang='ts'>
import { ref, reactive, computed } from 'vue'
let frist = ref('')
let last = ref('')
const name = computed(() => {
return frist.value + last.value
})
</script>
<style scoped>
</style>
对象类型
<template>
<input v-model="frist" type="text"> <br/>
<input v-model="last" type="text"> <br/>
<p>我的名字叫: {{name}}</p>
</template>
<script setup lang='ts'>
import { ref, reactive, computed } from 'vue'
let frist = ref('')
let last = ref('')
const name = computed({
get() {
return frist.value + last.value
},
set() {
frist.value + last.value
}
})
</script>
<style scoped>
</style>
购物车案例
<template>
<div>
<table width="500px" border>
<thead>
<tr>
<th>名称</th>
<th>数量</th>
<th>价格</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr :key="index" v-for="(item, index) in data">
<td>{{item.name}}</td>
<td><button @click="addNum(item, false)">-</button>{{item.num}}<button @click="addNum(item, true)">+</button></td>
<td>{{item.price}}</td>
<td><button @click="del(index)">删除</button></td>
</tr>
</tbody>
<tfoot>
<td></td>
<td></td>
<td></td>
<td>总价:{{tot}}</td>
</tfoot>
</table>
</div>
</template>
<script setup lang='ts'>
import { ref, reactive, computed } from 'vue'
type Shop = {
name: string
num: number
price: number
}
let tot = ref(0)
const data = reactive<Shop[]>([
{
name: '衣服',
num: 60,
price: 100
},
{
name: '裤子',
num: 10,
price: 88
},
{
name: '鞋子',
num: 12,
price: 1099
},
{
name: '袜子',
num: 19,
price: 10.9
}
])
const addNum = (item:Shop, type: boolean):void => {
if(item.num > 1 && !type) {
item.num--
}
if(item.num < 99 && type) {
item.num++
}
}
const del = (index: number):void => {
data.splice(index, 1)
}
tot = computed<number>(() => {
return data.reduce((prev, next) => {
return prev + (next.num * next.price)
}, 0)
})
// const total = () => {
// tot.value = data.reduce((prev,next) => {
// return prev + (next.num * next.price)
// },0)
// }
// total()
</script>
<style scoped>
</style>
watch 监听器
第一个参数是要监听的值 第二个参数是一个回调函数。回调函数有两个参数 一个是新值,一个是旧值
<template>
<input v-model="name" type="text" />
<p>{{name}}</p>
</template>
<script setup lang='ts'>
import { ref, watch } from 'vue'
let name = ref('张三')
watch(name, (newVal, oldVal) => {
console.log("新的:", newVal);
console.log("旧的:", oldVal);
})
</script>
<style scoped>
</style>
也可以监听多个 监听多个第一个参数变成一个数组,数组的值和两个参数是一一对应的
<template>
<input v-model="name" type="text" />
<input v-model="msg" type="text" />
<p>{{name}}</p>
</template>
<script setup lang='ts'>
import { ref, watch } from 'vue'
let name = ref('张三')
let msg = ref('李四')
watch([name, msg], (newVal, oldVal) => {
console.log("新的:", newVal);
console.log("旧的:", oldVal);
})
</script>
<style scoped>
</style>
watch还有第三个参数是一个options配置项是一个对象
<template>
<input v-model="name.frist.last.now" type="text" />
<p>{{name}}</p>
</template>
<script setup lang='ts'>
import { ref, watch } from 'vue'
let name = ref({
frist: {
last: {
now: '李四'
}
}
})
watch(name, (newVal, oldVal) => {
console.log("新的:", newVal);
console.log("旧的:", oldVal);
},{
deep: true, // ref深层次监听
immediate: true, // ref 第一次的时候也会监听
})
</script>
<style scoped>
</style>
如果是reactive就不用第三个参数也会监听
<template>
<input v-model="name.frist.last.now" type="text" />
<input v-model="name.frist.last.odd" type="text" />
<p>{{name}}</p>
</template>
<script setup lang='ts'>
import { ref, watch, reactive} from 'vue'
let name = reactive({
frist: {
last: {
now: '李四',
odd: '张三'
}
}
})
watch(name, (newVal, oldVal) => {
console.log("新的:", newVal);
console.log("旧的:", oldVal);
})
</script>
<style scoped>
</style>
如果是想只监听一个 把第一个参数改成一个函数并且把返回值改成你想要监听值
<template>
<input v-model="name.frist.last.now" type="text" />
<input v-model="name.frist.last.odd" type="text" />
<p>{{name}}</p>
</template>
<script setup lang='ts'>
import { ref, watch, reactive} from 'vue'
let name = reactive({
frist: {
last: {
now: '李四',
odd: '张三'
}
}
})
watch(() => name.frist.last.now, (newVal, oldVal) => {
console.log("新的:", newVal);
console.log("旧的:", oldVal);
})
</script>
<style scoped>
</style>
watchEffect
相当于简化版的watch 像监听谁就在里面使用谁
接收一个参数 该参数是一个回调函数 并且该回调函数里面的会在之前调用
<template>
<input v-model="name" type="text" />
<input v-model="name2" type="text" />
<p>{{name}}</p>
</template>
<script setup lang='ts'>
import { ref, watchEffect, reactive} from 'vue'
let name = ref<string>('张三')
let name2 = ref<string>('李四')
watchEffect((oninvalidate) => {
console.log("name", name.value);
oninvalidate(() => {
console.log("before");
})
})
</script>
<style scoped>
</style>
停止监听
再次调用就会停止监听
<template>
<input v-model="name" type="text" />
<input v-model="name2" type="text" />
<button @click="stopWatch">停止监听</button>
<p>{{name}}</p>
</template>
<script setup lang='ts'>
import { ref, watchEffect, reactive} from 'vue'
let name = ref<string>('张三')
let name2 = ref<string>('李四')
const stop = watchEffect((oninvalidate) => {
console.log("name", name.value);
oninvalidate(() => {
console.log("before");
})
})
const stopWatch = () => stop()
</script>
<style scoped>
</style>
组件的生命周期
什么是组件的生命周期,简单来说就是组件从创建到销毁的过程
注意:vue3组合式API中是没有 beforeCreate 和 Created 这两个生命周期钩子的
onBeforeMount()
在组件DOM实例渲染前调用,这里根组件还不存在
onMounted()
在组件的第一次选然后调用,该元素现在可用,允许直接DOM访问
onBeforeUpdate()
数据更新时调用,发生在虚拟 DOM 打补丁之前
onUpdated()
DOM更新后,updated
的方法即会调用
onBeforeUnmount()
在卸载组件实例之前调用。在这个阶段,实例仍然是完全正常的
onUnmounted()
卸载组件实例后调用。调用此钩子时,组件实例的所有指令都被解除绑定,所有事件侦听器都被移除,所有子组件实例被卸载
选项式 API | Hook inside setup |
beforeCreate | Not needed* |
created | Not needed* |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
errorCaptured | onErrorCaptured |
renderTracked | onRenderTracked |
renderTriggered | onRenderTriggered |
activated | onActivated |
deactivated | onDeactivated |
props 子传父
在使用 <script setup>
的单文件组件中,props 可以使用 defineProps()
宏来声明
const prop = defineProps(['msg', 'obj', 'arr'])
// App.vue 父组件
<template>
<Layout :msg = msg :obj = obj :arr = arr />
</template>
<script setup lang='ts'>
import { ref, reactive } from 'vue'
import Layout from './layout/index.vue'
const msg = ref('我是来自App组件的') // 传递参数
const obj = reactive({ //传递对象类型
name: '张三',
age: 18
})
const arr = reactive(['app传递的数组', 'vue', 'react', 'agluar']) //传递数组类型
</script>
<style scoped>
body, html, #app{
margin: 0;
padding: 0;
}
</style>
// 子组件 Layout.vue
<template>
<p>父组件app传递的参数:{{prop.msg}}</p>
<p>app传递的对象:{{prop.obj}}</p>
<ul>
<li v-for="(item, index) in prop.arr">{{item}}</li>
</ul>
</template>
<script setup lang='ts'>
import { ref, reactive } from 'vue'
const prop = defineProps(['msg', 'obj', 'arr'])
console.log(prop.msg);
console.log(prop.obj.name, prop.obj.age);
console.log(prop.arr);
</script>
<style scoped>
.content {
display: flex;
}
</style>
单向数据流
所有的props都遵循单向绑定的原则,根据父组件的更新而变化,自然的将新的状态向下流传给子组件,而不会逆向传递。
注意:每次父组件更新后,所有的子组件中的props都会被更新到最新值。所以不应该在子组件中更改一个prop
子传父 emit
使用defineEmits来派发事件 defineEmits(['自定义事件名称'])
// 子组件Layout.vue
<template>
<button @click="handleClick">点我传递</button>
</template>
<script setup lang='ts'>
import { ref, reactive } from 'vue'
const res = '子组件传递的参数'
const emit = defineEmits(['on-click'])
const handleClick = () => {
emit('on-click', res)
}
</script>
<style scoped>
.content {
display: flex;
}
</style>
父组件接受后直接使用
// 父组件 App.vue
<template>
<Layout @on-click = "callback" />
</template>
<script setup lang='ts'>
import { ref, reactive } from 'vue'
import Layout from './layout/index.vue'
const callback = (res: string) => {
console.log(123, res);
}
</script>
<style scoped>
body, html, #app{
margin: 0;
padding: 0;
}
</style>
父组件调用子组件的方法
在setup 语法糖中使用
// 子组件
// 更新文章分类
const show = async() => {
console.log(store.article);
const { data } = await getArticleClass()
console.log(data);
tableData.taDate = data.data
}
// 父组件需要使用该方法 使用defineExpose暴露出去让父组件接受
defineExpose({
show
})
// 父组件 引入
import Table from './compontent/Table.vue'
<Table ref="useCompontent" :tabDate="tabDate" />
const useCompontent = ref<any>();
const Confirm = async (res: Res) => {
dialogVisible.value = res.state
await insertArticle({
cate_name: res.cate_name,
cate_alias: res.cate_alias
})
// 更新视图------->> 更新文章分类
// 使用子组件的方法
useCompontent.value.show()
}