组件传值方法(vue3写法)
1.props
父组件传值给子组件
//父组件
<child :msg="msg" ></child>
<script>
import { ref, reactive } from "vue"
export default {
setup(){
// 创建一个响应式数据
const msg = ref(["这是传级子组件的信息"])
return { msg }
}
}
</script>
//子组件接收
export default {
props: {
msg2:{
type:String,
default:""
}
}
setup(props) {
console.log(props) // { msg:"这是传给子组件的信息" }
console.log(props.msg)
},
}
2.emit
子传父
//子组件
<template>
<input type="button" @click="sayHandle" value="子传父" />
</template>
<script>
import { ref } from "vue";
export default {
emits:['myClick'],
setup(props, { emit }) {
const sayHandle = () => {
emit("myClick", "我是子组件发送给父组件的消息");
};
return { sayHandle }
},
};
</script>
//父组件
<template>
<child @myClick="myClickHandle"></child>
</template>
<script>
import child from "./child.vue"
export default {
components: { child },
setup() {
const myClickHandle = (msg) => {
console.log(msg) // msg == 父组件收到的信息
}
}
}
3. 依赖注入(vue3)
可以让父组件向孙子组件传值
父组件 provide
import {ref,provide} from 'vue'
const root=ref('我是根组件')
// provide('键','值')
provide('rootMsg',root)
孙组件 inject
import {inject} from 'vue'
const sun=inject('rootMsg')
//console.log(r.value);
return {sun}
4. v-model
//父组件
<template>
<child v-model="msg" v-model:text="message2"></child>
</template>
import child from './components/v-model.vue'
import { ref } from "vue";
export default {
components:{child},
setup(){
let msg = ref("hello world!");
let message2 = ref("hello 2222");
return { msg,message2 }
}
}
</script>
//子组件
<template>
<div> {{modelValue}} </div>
</template>
export default {
props: {
//父组件里面 v-model冒号后面不写值,默认就是modelValue
modelValue: {
type: String,
},
text:{
type: String,
}
}
}