Niffler

X2.10 16340246-Vue父子组件之间的参数传递

Posted By 16340246

在构建 Vue 应用时,我们会定义多个组件,而组件之间常常需要传递参数,下面介绍一些父子组件之间的传递参数方法和示例。

父组件向子组件传递参数

在下面的示例中,子组件将接收父组件传来的 message, color, fontSize 这 3 个参数,设定子组件的内容、字体大小和字体颜色,我们要把这些参数写到 props 里面。

我们可以以字符串数组的形式列出 props

props: ['message', 'color', 'fontSize']

但是,通常你希望每个 prop 都有指定的值类型。这时,你可以以对象形式列出 prop,这些属性的名称和值分别是 prop 各自的名称和类型:

props: {
  message: String,
  color: String,
  fontSize: Number
}

创建一个子组件 Child.vue,放在 src/components/ 文件夹,在子组件创建它的定义如下:

<template>
  <div>
    <p :style="`color: ${color}; font-size: ${fontSize}px;`">子组件内容:{{ message }}</p>
  </div>
</template>

<script>
export default {
  // 要接收的参数
  props: {
    message: String,
    color: String,
    fontSize: Number
  }
}
</script>

父组件是 App.vue,在这里向子组件传递了多个参数组合,内容如下:

<template>
  <div id="app">
    <Child :message="'A message from parent'" :fontSize="10" :color="'#f00'"></Child>
    <Child :message="'A message from parent'" :fontSize="12" :color="'#f30'"></Child>
    <Child :message="'A message from parent'" :fontSize="14" :color="'#f60'"></Child>
    <Child :message="'A message from parent'" :fontSize="16" :color="'#f90'"></Child>
    <Child :message="'A message from parent'" :fontSize="18" :color="'#fc0'"></Child>
    <Child :message="'A message from parent'" :fontSize="20" :color="'#ff0'"></Child>
  </div>
</template>

<script>
// 引入子组件 Child
import Child from './components/Child'
export default {
  name: 'App',
  components: {
    Child
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

最后结果:

parent-child

子组件向父组件传递参数

在本示例中,子组件有一个按钮,点击这个按钮后,子组件将向父组件传递一个数字 num,父组件中的 count 会增加 num

child-parent

父组件通过定义事件 @change="addCount" 接收子组件传来的数据,调用 addCount 来处理:

<template>
  <div id="app">
    <p>父组件:{{ count }}</p>
    <Child @change="addCount"></Child>
  </div>
</template>

<script>
// 引入子组件 Child
import Child from './components/Child'
export default {
  name: 'App',
  components: {
    Child
  },
  data () {
    return {
      count: 0
    }
  },
  methods: {
    addCount (num) {
      this.count += num
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

在子组件中,点击按钮会触发 toParent 方法,使用 this.$emit('change', 2) 来触发父组件的 change 事件并传递一个数字 2:

<template>
  <div>
    <el-button type="primary" @click="toParent()">子组件按钮</el-button>
  </div>
</template>

<script>
export default {
  methods: {
    toParent () {
      this.$emit('change', 2)
    }
  }
}
</script>

刷新页面,现在点击一次按钮就可以看到数字增加 2 了。显然,我们也用 this.$emit 来调用父组件的方法.