2. Vue 向子组件传递参数

Vue 向子组件传递参数

Prop 是你可以在组件上注册的一些自定义 attribute。当一个值传递给一个 prop attribute 的时候,它就变成了那个组件实例的一个属性。为了给博文组件传递一个标题,我们可以用一个 props 选项将其包含在该组件可接受的 prop 列表中:

<div id="app">
  <blog-info
  	v-for="info in infos"
    v-bind:info="info"
  ></blog-info>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
Vue.component('blog-info', {
  props: ['info'],
  template: `
    <div class="blog-post">
        <h3>{{ info.title }}</h3>
        <div v-html="info.content"></div>
    </div>
  `
})
new Vue({
  el: '#app',
  data: {
    infos: [
      { id: 1, title: 'My journey with Vue', content:'1..' },
      { id: 2, title: 'Blogging with Vue', content:'2..' },
      { id: 3, title: 'Why Vue is so fun', content:'3..' }
    ]
  }
})
Vue 3中,父组件向子组件传递参数的方式主要有以下两种: 1.使用v-bind绑定数值,然后通过props在子组件中接收使用。具体步骤如下:[^1] - 在父组件中,使用v-bind将数值绑定到子组件上: ```html <template> <div> <child-component :message="msg"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { name: 'ParentComponent', components: { ChildComponent }, data() { return { msg: '父组件向子组件传参示例' } } } </script> ``` - 在子组件中,使用props定义接收的属性名称,然后通过template中的插值语法将props中的数值显示出来: ```html <template> <div> <p>{{ message }}</p> </div> </template> <script> import { defineProps } from 'vue'; export default { name: 'ChildComponent', props: { message: { type: String, default: '' } }, setup(props) { return { message: props.message } } } </script> ``` 2.使用defineProps在子组件中定义props属性,然后在父组件中通过v-bind绑定数据到子组件的props属性中。具体步骤如下: - 在子组件中,使用defineProps定义props属性接收父组件传递的参数: ```html <template> <div> <p>{{ type }}</p> </div> </template> <script> import { defineProps } from 'vue'; export default { name: 'ChildComponent', emits: ['update:type'], props: defineProps({ type: { type: String, default: 'edit' } }), methods: { updateType() { this.$emit('update:type', 'update'); } } } </script> ``` - 在父组件中,使用v-bind绑定数值到子组件的props属性中,并在需要更新时使用v-on监听子组件的自定义事件来进行更新。 ```html <template> <div> <child-component :type="type" @update:type="handleUpdate"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { name: 'ParentComponent', components: { ChildComponent }, data() { return { type: 'edit' } }, methods: { handleUpdate(data) { this.type = data; } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值