Vue3语法基本使用
1、watch 使用
watch(监听数据源,执行函数,[配置参数])
//配置参数: 立即执行 深度监听
{immediate: true, deep: true }
1.1 监听基本数据类型单一数据源
<script setup>
import {ref, watch} from 'vue'
let name = ref('张麻子')
//监听器
watch(name,(newVal,oldVal)=>{
console.log('变量发生了改变...',newVal);
})
</script>
1.2 监听引用数据类型单一数据源
<script setup>
import {reactive, ref, watch} from 'vue'
let user = reactive({name:'张三',age:14})
//监听器
watch(()=>user.name,(newVal,oldVal)=>{
console.log('对象user中的name属性发生了变化..',newVal);
})
</script>
1..3 监听引用数据类型 多数据源[深度监听]
<template>
<div>
<button @click="addNum()"> 添加随机数</button>
<div v-for="item in nums" :key="item">{{ item }}</div>
</div>
</template>
<script setup>
import { reactive, ref, watch } from 'vue'
let nums = reactive([]);
//添加随机数
const addNum = () => {
let num = Math.ceil(Math.random() * 100);
nums.push(num);
}
//监听数组变化-深度监听
watch(()=>nums,(newVal,oldVal)=>{
console.log('nums数组发生了变化..',newVal);
},{deep:true})
</script>
2、组件使用
创建 src/components/Son.vue App.vue中导入并使用该组件 vue3.2 中当我们导入子组件时,setup语法糖会自动去注册该组件,所以注册语句不用写了。
<template>
<div>
<son></son>
</div>
<script setup>
import Son from './components/Son.vue'
</script>
3、组件通信
3.1 父传子 defineProps
- 父组件
<template> <div> <Son class="box" title="我是父组件传递的标题" :likes="likes"></Son> </div> </template> <script setup> import Son from './components/Son.vue' let likes = ['张三','李四'] </script> - 子组件
<script setup> const props=defineProps({ title:{ type:String, default:'' }, likes:{ type:Array, default:()=>[] } }) </script>3.2 子传父 defineEmits
- 子组件
<template> <div> <button @click="sendData">传递数据</button> </div> </template> <script setup> //定义自定义事件 const emit = defineEmits(['send']) //自己的事件执行函数 const sendData = () => { //执行自定义事件 emit('send', '我是儿子组件传递的数据') } </script>- 父组件
<template> <div> <Son class="box" @send="getData" ></Son> </div> </template> <script setup> import Son from './components/Son.vue' //触发自定义事件-接收数据 const getData = (data)=>{ console.log(data); } </script>
- 父组件
- 子组件
sunshine15666

浙公网安备 33010602011771号