zoukankan      html  css  js  c++  java
  • 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
    本文版权归作者和博客园共有,欢迎转载,转载时保留原作者和文章地址即可。
  • 相关阅读:
    【转载】Chrome 0day漏洞:不要用Chrome查看pdf文件
    内网渗透闲谈
    Sticky Fingure安装教程
    局域网下交换机配置
    Access 2010 应用基础 单元三:SQL查询
    ESP8266 wifi干扰、钓鱼实现
    这是谁的锅
    svn/git的diff、patch
    sublime开发php必备工具集合(mac)
    gcc学习笔记
  • 原文地址:https://www.cnblogs.com/maggieq8324/p/15262309.html
Copyright © 2011-2022 走看看