vue3基础 —— 子传父
须知:vue里子组件无法改变父组件的值思路:1. 父组件定义数据 ——const data = ref(false)2.把值传递给子组件 —— :sendData = "data"3.子组件接收数据,使用、修改完成后 —— props: ["sendData"] ——const a = props.sendData ——a =true4.触发父组件事件,传值 ——emit("emitEffect"
·
须知:vue里子组件无法改变父组件的值
思路:
1. 父组件定义数据 —— const data = ref(false)
2. 把值传递给子组件 —— :sendData = "data"
3. 子组件接收数据,使用、修改完成后 —— props: ["sendData"] —— const a = props.sendData —— a = true
4. 触发父组件事件,传值 —— emit("emitEffect", { emit: a })
5. 被触发的父组件,接收值,并更新自己最开始定义的数据 —— @emitEffect = "changeData" —— const changeData = (value) => { data = value.a }
例子:
父组件:
<template>
<div class="index">
<div class="index__nav">
<Indexnav :changeNavFu=changeNavFu @changeNavfu="changeNav" />
</div>
</div>
</template>
<script>
import { ref } from 'vue'
import Indexnav from './Indexnav.vue'
export default {
name: 'index',
components: { Indexnav, Indextab },
setup () {
const changeNavFu = ref(false)
const changeNav = (val) => {
changeNavFu.value = val.data
console.log(val) // {data:false}
}
return { changeNavFu, changeNav }
}
}
</script>
<style lang="scss" scoped>
.index{
font-size: .13rem;
overflow: hidden;
width: 100%;
height: 100vh;
&__nav {
width: 2rem;
}
}
</style>
子组件:
<template>
<div class="Indexnav" :style="isCollapse?'width:.63rem':''">
<div class="Indexnav__header" @click="changeNav">
<div :class="isCollapse?'sider-toggler':'sider-toggler active'"></div>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'Indexnav',
components: { Location },
props: ['changeNavFu'],
setup (props, { emit }) { // 一定要记得把props和emit传入setup函数
const isCollapse = ref(props.changeNavFu)
const changeNav = () => {
isCollapse.value = !isCollapse.value
emit('changeNavfu', { data: isCollapse.value })
}
return { isCollapse, changeNav }
}
}
</script>
<style lang="scss" scoped>
@import '../../assets/fonts/iconfont.css';
.Indexnav{
position: absolute;
width: 2rem;
top: 0;
left: 0;
height: 100%;
box-shadow: .01rem .02rem .1rem rgba(0,0,0,.5);
border-right: 1px solid #f2f4f9;
transition: all .1s linear;
}
</style>
更多推荐
已为社区贡献2条内容
所有评论(0)