1.props
//接收父组件数据
//使用单文件组件语法 props 传值方法 要使用defineProps方法,这个是不需要引入的
//子组件
<script setup>
let prop = defineProps({
propA: {
type: String, //数据类型
required: true, //是否必填
default: '你好,Vue3', //默认值
validator(value) {//验证数值
// 这个值必须与下列字符串中的其中一个相匹配
return ['你好,Vue3', 'warning', 'danger'].includes(value);
}
},
propB: {
type: Object, //数据类型
default(){ //默认值 引入类型数据 要使用函数方法返回值
return {msg:"你好"}
},
}
});
</script>
<template>
<h1>{{ propA }}</h1>
<h1>{{ propB.msg }}</h1>
</template>
//父组件
let propA=ref("你好,Vue3")
let propB=reactive({msg:"你好,Vue3"})
<template>
<HelloWorld ref="hello" :propA="propA" :propB="propB"></HelloWorld>
</template>
2. emit
//用于子组件传父组件
//defineEmit 自定义事件
//子组件
<script setup>
const emit= defineEmits(['changes'])
const clickThis = () => {
emit('changes',"我很好,Vue3") //可支持传多个参数 例如emit('changes',"1","2")
}
</script>
<template>
<button @click="clickThis">按钮</button>
</template>
//父组件
<script setup>
let changes=(pyload)=>{ //接收多个参数 (pyload,pyload1)
propB.msg=pyload
console.log("触发了")
}
</script>
<template>
<HelloWorld @changes="changes"></HelloWorld>
</template>
3.provide/inject 适用于祖代传后代
祖代组件
<script setup>
import {ref,reactive,provide} from "vue"
let provideA=ref("你好,Vue3") //想要数据具有响应式 必须要ref or reactive 定义
let provideB=reactive({msg:"你好,Vue3"})
provide("provideA",provideA)
provide("provideB",provideB)
<script>
后代组件
<script setup>
import {inject } from 'vue';
let provideA=inject("provideA")
let provideB=inject("provideB")
<script>
4.访问子组件实例
//访问子组件实例数据
//父组件
<script setup>
import {ref,onMounted,reactive,provide} from "vue"
let hello=ref(null)//变量名称要与 组件ref 名称一致
onMounted(() => {
console.log(hello.value.count);//0
console.log(hello.value.count2); //1
console.log(hello.value.count3); //未定义
})
</script>
<HelloWorld ref="hello"></HelloWorld>
子组件
<script setup>
let count = ref(0); //如果数据需要响应式 则需要 ref or reactive 赋值
let count2=1
let count3=1
defineExpose({//需要使用defineExpose方法把数据暴露出去才能访问
count,
count2
})
</script>
5访问父组件实例
//子组件
<script setup>
import { ref, getCurrentInstance} from 'vue';
// 这只适用于开发环境 线上环境 ctx 获取的示例不一致
//let { ctx} = getCurrentInstance();
//console.log(ctx.$parent.propA = 'warning');
//console.log(ctx.$parent.fun());
let that=getCurrentInstance()
console.log(that.parent.exposed.propA.value)
console.log(that.parent.exposed.fun())
</script>
// 父组件
<script setup>
let propA=ref("你好,Vue3")
function fun(){
console.log("我被访问了")
}
defineExpose({ //父组件也需要把被访问的数据暴露出去才能被访问
propA,
fun
})
</script>
6.vuex
import { useStore } from 'vuex';
const store = useStore();
console.log(store.state.count)//存储数据
console.log(store.commit("increment","参数")) //同步方法
console.log(store.getters.count)//计算属性
console.log(store.dispatch("increment","参数")) //异步方法
console.log(store.state.modulesName)// 模块化