Vue使用props父子组件传递数据

栏目: JavaScript · 发布时间: 4年前

内容简介:父组件子组件父组件

父组件

<template>
   <div>
      <demo :msg='msgData' :math = 'mathData' ></demo>
   </div>
</template>
<script>
import Demo from './Demo.vue'
   export default {
     data () {
       return  {
          msgData:'从父组件接收来的数据',
          mathData : 2
       }
     },
     components : {
       Demo
     }
   }
</script>

子组件

<template>
  <div>
     <p>{{msg}}</p>
     <p>{{math}}</p>
  </div>
</template>

<script>
export default {
  name: 'demo',
  props: [ 'msg' , 'math'],
}
</script>

父子组件传递函数

父组件

<template>
   <div>
      <demo :fn = 'myFunction' ></demo>
   </div>
</template>
<script>
import Demo from './Demo.vue'
   export default {
     components : {
       Demo
     },
     methods: {
       myFunction () {
           console.log('vue')
       }
     }
   }
</script>

子组件

<template>
  <div>
     <button @click='fn'>按钮</button>
  </div>
</template>

<script>
export default {
  name: 'demo',
  props: [ 'fn' ],
}
</script>

另外,当传递的数量一旦多到已经让原子化不再结构清晰的时候,通过一个对象传递显得更为简洁明了。

父子组件传递对象数据

父组件

<template>
   <div>
      <demo v-bind= 'msg'  ></demo>
   </div>
</template>
<script>
import Demo from './Demo.vue'
   export default {
     components : {
       Demo
     },
     data () {
       return {
         msg : {a:1,b:2}
       }
     }
   }
</script>

子组件

<template>
  <div>
     <button>按钮</button>
  </div>
</template>

<script>
export default {
  name: 'demo',
  props: ['a','b'],
  created () {
     console.log(this.a)
     console.log(this.b)
  },
}
</script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

How Great Decisions Get Made

How Great Decisions Get Made

Maruska, Don / 2006-2 / $ 20.28

All too often, solving tough work issues can become a tug of war as clashing departments, priorities, personality styles, and other concerns threaten to destroy any possibility of a successful conclus......一起来看看 《How Great Decisions Get Made》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码