Vue - 父子组件间的参数传递

时间:2021-09-13
本文章向大家介绍Vue - 父子组件间的参数传递,主要包括Vue - 父子组件间的参数传递使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前言

记录下Vue中父子组件中的参数传递


父组件向子组件传递参数(props)

  • App.vue
<template>
  <Test @sub-event="onTestClick" :url="theme6" />
</template>
<script>
import Test from './components/test.vue'
import theme6 from './assets/home/theme6.jpg'

export default {
  name: 'App',
  components: {
    Test
  },
  setup () {
    return {
      theme6
    }
  }
}
</script>
  • test.vue
<template>
  <img :src="url" />
</template>

<script>
export default {
  name: 'test',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  setup (props, context) {
    console.log(props.url)
  }
}
</script>
  • 结果


子组件向父组件传递参数(自定义事件)

  • app.vue
<Test @sub-event="onTestClick" :url="theme6" />

export default {
	setup () {
	 /**
      * 自定义事件监听与参数获取
      * @param event
      */
	  function onTestClick (event) {
	    console.log(event)
	  }
	  return {
	    theme6,
	    onTestClick
	  }
	}
}

setup自定义事件

test.vue

<template>
  <img @click="onImgClick" :src="url" class="size"   />
</template>

<script>

const param = 1

export default {
  name: 'test',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  setup (props, context) {
    console.log(props.url)
    /**
     * 写法一: setup自定义事件
     * 自定义事件与参数传递
     */
    function onImgClick () {
      context.emit('sub-event', param)
    }
    return {
      onImgClick
    }
  }
}
</script>

methods自定义事件

  • test.vue
<template>
  <img @click="onImgClick" :src="url" class="size"   />
</template>

<script>
const param = 1
export default {
  name: 'test',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  methods: {
    /**
     * 写法二: methods自定义事件
     * 自定义事件与参数传递
     */
    onImgClick () {
      this.$emit('sub-event', param)
    }
  }
}
</script>
  • setupmethods中定义本质相同,自定义事件点击结果如下:


- End -
梦想是咸鱼
关注一下吧
以上为本篇文章的主要内容,希望大家多提意见,如果喜欢记得点个推荐哦
作者:Maggieq8324
本文版权归作者和博客园共有,欢迎转载,转载时保留原作者和文章地址即可。

原文地址:https://www.cnblogs.com/maggieq8324/p/15262309.html