Vue3组件间的传值案例(props,emit,ref,attrs,inject在setup script标签两个场景中的使用)

Vue3组件间的传值案例

一.知识补充

如下整理了,Vue3传值过程中,propsemitrefattrsinjectsetup script 标签中和不在setup script 标签中的案例

1.setup

setup 方法接受两个参数 setup(props, context)

props 是父组件传给组件的数据

context(上下文) 中包含了一些常用属性:

  • attrs 表示由上级传向该组件,但并不包含在 props 内的属性
<!-- parent.vue -->
<Child msg="hello world" :name="'child'"></Child>
/* child.vue */
export default {
  props: { name: String },
  setup(props, context) {
    console.log(props) // {name: 'child'}
    console.log(context.attrs) // {msg: 'hello world'}
  },
}
  • emit用于在子组件内触发父组件的方法
<!-- parent.vue -->
<Child @toggle="toggle"></Child>
/* child.vue */
export default {
  setup(_, context) {
    context.emit('toggle')
  },
}
  • slots用来访问被插槽分发的内容,相当于 vm.$slots
<!-- parent.vue -->
<Child>
  <template v-slot:header>
    <div>header</div>
  </template>
  <template v-slot:content>
    <div>content</div>
  </template>
  <template v-slot:footer>
    <div>footer</div>
  </template>
</Child>
/* child.vue */
export default {
  setup(_, context) {
    const { header, content, footer } = context.slots
    return () => h('div', [h('header', header()), h('div', content()), h('footer', footer())])
  },
}

2.script setup

script setup是 Vue3 的一个新语法糖,相比于普通的语法,简化了组合式API必须return的写法,拥有更好的运行时性能。

  1. 声明的内容可以直接在模板中使用
  2. 自动注册组件
  3. 动态组件,应该使用动态的:is来绑定
  4. 必须使用 definePropsdefineEmits API 来声明 props 和 emits
  5. script setup的组件是默认关闭的,需要defineExpose明确要暴露的属性
  6. 通过 useSlotsuseAttrs 两个辅助函数使用slotsattrs
  7. script setup中可以使用顶层 await。结果代码会被编译成 async setup()

3.attrs 属性可以看做 props 的加强版

区别:

  1. props 要先声明才能取值,attrs 不用先声明
  2. props 声明过的属性,attrs 里不会再出现
  3. props 不包含事件,attrs 包含
  4. props 支持 string 以外的类型,attrs 只有 string 类型
    (具体可见官网)

二.案例

💥prps

✨方式一
父组件
<template>
    <div>
        我是父组件
        <!-- 传递给子组件 -->
        <ChildrenVue :msg='msg' />
    </div>
</template>
<script>
import ChildrenVue from '../components/Children.vue';
import { ref } from 'vue'
export default {
    //注册子组件
    components: {
        ChildrenVue
    },
    setup() {
        //向子组件传递的参数
        const msg = ref('哈喽哈喽')
        return {
            msg
        }
    }
}
</script>
  
子组件
<template>
    <div>
        我是子组件
        <!-- 使用参数 -->
        <h1> {{msg}}</h1>
    </div>
</template>
<script>
export default {
    //接收参数
    props: ['msg'],
    setup(props) {
        //获取父组件传递的参数
        const msg = props.msg
        console.log(props.msg);
        return {
            msg
        }
    }
}
</script>
✨方式二
父组件
<template>
    <div>
        我是父组件
        <!-- 传递给子组件 -->
        <ChildrenVue :msg='msg' />
    </div>
</template>
<script setup>
import ChildrenVue from '../components/Children.vue';
import { ref } from 'vue'
// 传递参数
const msg = ref('哈喽哈喽')
</script>
子组件
<template>
    <div>
        我是子组件
        <!-- 使用参数 -->
        <h1> {{msg}}</h1>
    </div>
</template>
<script setup>
const props = defineProps({
    // 写法一
    // msg: String
    //写法二
    msg: {
        type: String,
        default: ''
    }
})
console.log(props.msg);
</script>

💥emit

✨方式一
父组件
<template>
    <div>
        我是父组件
        <ChildrenVue @myClick='onMyClick' />
    </div>
</template>
<script setup>
import ChildrenVue from '../components/Children.vue';
//父组件定义自定义事件onMyClick
//监听子组件的自定义事件myClick
const onMyClick = (msg) => {
    //获取参数
    console.log(msg);
}
</script>
子组件
<template>
    <div>
        我是子组件
        <button @click="handleClick">按钮</button>
    </div>
</template>
<script setup>
import { defineEmits } from 'vue'
//获取emit
const emit = defineEmits()
//定义点击事件handleClick
//定义自定义事件myClick
//传递信息
const handleClick = () => {
    emit('myClick', '我是子组件给父组件的')
}
</script>
✨方式二
父组件
<template>
    <div>
        我是父组件
        <ChildrenVue @myClick='onMyClick' />
    </div>
</template>
<script>
//引入子组件
import ChildrenVue from '../components/Children.vue';
export default {
    //注册
    components: {
        ChildrenVue
    },
    setup() {
        //定义自定事件触发子组件,获取信息
        const onMyClick = (msg) => {
            console.log(msg);
        }
        return {
            onMyClick
        }
    }
}
</script>
子组件
<template>
    <div>
        我是子组件
        <button @click="handleClick">按钮</button>
    </div>
</template>
<script>
export default {
    setup(props, context) {
        const handleClick = () => {
            context.emit('myClick', '我是子组件给父组件的')
        }
        return {
            handleClick
        }
    }
}
</script>

💥ref

✨方式一
父组件
<template>
    <div>
        我是父组件
        <!-- 定义ref 获取子组件的属性和方法 -->
        <ChildrenVue ref='childrenRef' />
        <button @click="show">获取子组件的属性和方法</button>
    </div>
</template>
<script>
//引入子组件
import ChildrenVue from '../components/Children.vue';
import { ref } from 'vue'
export default {
    //注册
    components: {
        ChildrenVue
    },
    setup() {
        //声明子组件的ref
        const childrenRef = ref(null)
        const show = () => {
            //使用子组件的属性和方法
            //通过 ref.value.子组件的属性or方法
            console.log(childrenRef.value.title);
            childrenRef.value.toggle()
        }
        return {
            childrenRef,
            show
        }
    }
}
</script>
子组件
<template>
    <div>
        我是子组件
    </div>
</template>
<script>
export default {
    setup() {
        const title = '我是子组件的属性'
        const toggle = () => {
            console.log('我是子组件的方法');
        }
        return {
            title,
            toggle
        }
    }
}
</script>
✨方式二
父组件
<template>
    <div>
        我是父组件
        <!-- 定义ref 获取子组件的属性和方法 -->
        <ChildrenVue ref='childrenRef' />
        <button @click="show">获取子组件的属性和方法</button>
    </div>
</template>
<script setup>
//引入子组件
import ChildrenVue from '../components/Children.vue';
import { ref } from 'vue'
//声明子组件的ref
const childrenRef = ref(null)
const show = () => {
    //使用子组件的属性和方法
    //通过 ref.value.子组件的属性or方法
    console.log(childrenRef.value.title);
    childrenRef.value.toggle()
}
</script>
子组件
<template>
    <div>
        我是子组件
    </div>
</template>
<script setup>
const title = '我是子组件的属性'
const toggle = () => {
    console.log('我是子组件的方法');
}
defineExpose({
    // 将想要暴露的属性和方法名称
    title, toggle
})
</script>

💥attrs

✨方式一
父组件
<template>
    <div>
        我是父组件
        <ChildrenVue :msg='msg' />
    </div>
</template>
<script setup>
//引入子组件
import ChildrenVue from '../components/Children.vue';
import { ref } from 'vue'
const msg = ref('我是父组件传递的信息')
</script>
子组件
<template>
  <div>
    我是子组件
    {{ attrs.msg }}
  </div>
</template>
<script setup>
import { useAttrs } from "vue";
const attrs = useAttrs();
console.log(attrs.msg);
</script>
✨方式二
父组件
<template>
  <div>
    我是父组件
    <ChildrenVue :msg1="msg1" :name="msg2" @click="toggle"/>
  </div>
</template>
<script>
import ChildrenVue from "../components/Children.vue";
import { ref } from "vue";
export default {
  components: { ChildrenVue },
  setup() {
    const msg1 = ref("我是父组件传递的信息1");
    const msg2 = ref("我是父组件传递的信息2");
    //传递的方法
    const toggle = () => {
      console.log("hhhhh");
    };
    return {
      msg1,
      msg2,
      toggle,
    };
  },
};
</script>
子组件
<template>
  <div>
    我是子组件
    {{ name }}
  </div>
</template>
<script>
export default {
  props: { name: String },
  setup(props, context) {
    //props传递的参数    name:'我是父组件传递的信息2'
    console.log(props);
    //attrs传递的参数    msg1: '我是父组件传递的信息1'
    console.log({ ...context.attrs });
  }
};
</script>

💥inject

父组件
<script setup>
   import { provide } from "vue"
   provide("name", "hello")
</script>
子组件
<script setup>
   import { inject } from "vue"
   const name = inject("name")
   console.log(name) // hello
</script>
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue 3 ,可以通过 `props`、`emit` 和 `provide / inject` 三种方式来实现组件的数据传递。 1. 使用 `props` 传递数据 在父组件使用 `props` 属性来传递数据,子组件通过 `props` 接收数据。父组件可以在子组件使用 `v-bind` 来绑定数据。 ```vue <!-- 父组件 --> <template> <div> <ChildComponent :message="msg" /> </div> </template> <script> import ChildComponent from "./ChildComponent.vue"; export default { components: { ChildComponent, }, data() { return { msg: "Hello, World!", }; }, }; </script> <!-- 子组件 --> <template> <div> {{ message }} </div> </template> <script> export default { props: { message: String, }, }; </script> ``` 2. 使用 `emit` 传递事件 在子组件使用 `$emit` 方法触发事件,父组件可以通过 `v-on` 监听事件并处理。 ```vue <!-- 子组件 --> <template> <div> <button @click="sendMessage">发送消息</button> </div> </template> <script> export default { methods: { sendMessage() { this.$emit("send", "Hello, World!"); }, }, }; </script> <!-- 父组件 --> <template> <div> <ChildComponent @send="handleSend" /> </div> </template> <script> import ChildComponent from "./ChildComponent.vue"; export default { components: { ChildComponent, }, methods: { handleSend(message) { console.log(message); // 输出:Hello, World! }, }, }; </script> ``` 3. 使用 `provide / inject` 提供和注入依赖 `provide / inject` 可以在祖先组件提供数据,在后代组件注入数据,可以跨越多个层级传递数据。 ```vue <!-- 祖先组件 --> <template> <div> <GrandchildComponent /> </div> </template> <script> import { provide } from "vue"; import ChildComponent from "./ChildComponent.vue"; export default { components: { GrandchildComponent, }, setup() { const message = "Hello, World!"; provide("message", message); }, }; </script> <!-- 子组件 --> <template> <div> <ChildComponent /> </div> </template> <script> import { inject } from "vue"; import GrandchildComponent from "./GrandchildComponent.vue"; export default { components: { GrandchildComponent, }, setup() { const message = inject("message"); return { message }; }, }; </script> <!-- 后代组件 --> <template> <div> {{ message }} </div> </template> <script> export default { setup(props, { attrs, slots, emit }) { const message = inject("message"); return { message }; }, }; </script> ``` 以上是三种常见的组件数据传递方式,在实际开发可以根据具体情况选择合适的方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月落乌江

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值