在 Vue 中传递参数可以通过以下几种方式:

  1. props

props 是 Vue 组件中的一个属性,用来接收父组件传递过来的数据。在父组件中使用 v-bind 指令将数据传递给子组件,子组件通过 props 属性接收数据。

父组件中:

<template>
  <child-component :message='hello'></child-component>
</template>
<script>
export default {
  data () {
    return {
      hello: 'Hello, World!'
    }
  }
}
</script>

子组件中:

<template>
  <div>{{ message }}</div>
</template>
<script>
export default {
  props: {
    message: String
  }
}
</script>
  1. $emit

$emit 是 Vue 实例中的一个方法,用来触发自定义事件,并向父组件传递数据。在子组件中使用 $emit 方法触发事件,在父组件中使用 v-on 指令监听事件并接收数据。

子组件中:

<template>
  <button @click='sendData'>Send Data</button>
</template>
<script>
export default {
  methods: {
    sendData () {
      this.$emit('my-event', 'Hello, World!')
    }
  }
}
</script>

父组件中:

<template>
  <div>
    <child-component @my-event='handleEvent'></child-component>
    <div>{{ message }}</div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      message: ''
    }
  },
  methods: {
    handleEvent (data) {
      this.message = data
    }
  }
}
</script>
  1. $route

$route 是 Vue 路由中的一个对象,用来获取当前路由的信息。在路由跳转时,可以通过 $route 对象传递参数。

在路由配置中:

{
  path: '/user/:id',
  name: 'user',
  component: UserComponent
}

在组件中:

<template>
  <div>{{ id }}</div>
</template>
<script>
export default {
  computed: {
    id () {
      return this.$route.params.id
    }
  }
}
</script>

以上是 Vue 中传递参数的常用方式,根据实际需求选择合适的方式。

Vue.js 传递参数的常用方法

原文地址: https://www.cveoy.top/t/topic/luCY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录