返回

Vue 核心基础:父组件传递属性与获取查询参数的正确方式

前端

Vue.js 核心基础详解:父组件传参和获取查询参数

父组件传递属性

在 Vue.js 中,父组件可以向子组件传递属性,实现数据共享和功能复用。以下两种方式可以实现:

1. 使用 props 选项

父组件使用 props 选项声明需要传递的属性,子组件使用 this.$props 访问父组件传递的属性。

示例:

<!-- 父组件 -->
<template>
  <child-component :name="name" :age="age"></child-component>
</template>

<!-- 子组件 -->
<script>
export default {
  props: ['name', 'age'],
  data() {
    return {
      // ...
    }
  },
  methods: {
    // ...
  }
}
</script>

2. 使用 slot 选项

父组件使用 slot 选项定义插槽,子组件使用 <slot> 元素填充父组件的插槽。

示例:

<!-- 父组件 -->
<template>
  <child-component>
    <template v-slot:header>
      <h1>{{ title }}</h1>
    </template>
    <template v-slot:content>
      <p>{{ content }}</p>
    </template>
  </child-component>
</template>

<!-- 子组件 -->
<template>
  <div>
    <slot name="header"></slot>
    <slot name="content"></slot>
  </div>
</template>

获取查询参数

Vue.js 中,通过 $route 对象获取当前路由信息,然后使用 $route.query 对象访问查询参数。通过 this.$route.query.参数名 获取特定查询参数的值。

示例:

获取 id 查询参数:this.$route.query.id

常见问题解答

1. 父组件中如何声明 props 选项?

<template>
  <child-component :name="name" :age="age"></child-component>
</template>

2. 子组件中如何使用 this.$props 访问父组件传递的属性?

export default {
  props: ['name', 'age'],
  data() {
    return {
      // ...
    }
  },
  methods: {
    // ...
  }
}

3. 父组件中如何使用 slot 选项定义插槽?

<template>
  <child-component>
    <template v-slot:header>
      <h1>{{ title }}</h1>
    </template>
    <template v-slot:content>
      <p>{{ content }}</p>
    </template>
  </child-component>
</template>

4. 子组件中如何使用 <slot> 元素填充父组件的插槽?

<template>
  <div>
    <slot name="header"></slot>
    <slot name="content"></slot>
  </div>
</template>

5. 如何获取 id 查询参数?

this.$route.query.id

总结

掌握 Vue.js 的父组件传递属性和获取查询参数是构建强大、灵活应用的关键。通过理解这些核心基础,开发者可以轻松实现数据共享、功能复用和获取 URL 查询参数。