Vue子父组件之间数据传递方式

来源:互联网 发布:python 微信 编辑:程序博客网 时间:2024/06/11 13:05

Vue子父组件之间数据传递方式

子组件向父组件

在子组件通过 this.$emit(“事件名称”,传递的数据1,数据2,…);

<template>  <div class="sonToFather">      <input placeholder="please input" v-model="sendDatas"/>      <button v-on:click="sendData">Send</button>  </div></template><script>export default {  name: 'sonToFather',  data:function(){    return {      sendDatas:"",    }  },  methods: {    sendData:function(e){      this.$emit("sonToFather",this.sendDatas);//通过emit传递      e.preventDefault();    }  },}</script><style scoped></style>

然后在父组件中通过该子组件中 v-on:事件名=”接收方法” 来接收

<template>  <div id="app">  <!-- 获得子组件传递过来的数据 -->    <sonToFather v-on:sonToFather="getSonData"></sonToFather>  </div></template><script>import SonToFather from './components/SonToFather'export default {  name: 'app',  components: {    SonToFather  },  methods:{    getSonData:function(text){      alert(text);  }}</script><style></style>

父组件向子组件

父组件向子组件传递通过数据绑定的形式,在父组件中将要传递的数据绑定一下 v-text=”要传递的数据”

<template>  <div id="app"> <!-- 父组件给子组件传递数据 -->    <fatherToSon v-text="fatherToSonData"></fatherToSon>  </div></template><script>import FatherToSon from './components/FatherToSon'export default {  name: 'app',  data:function(){    return{      fatherToSonData:""    }  },  components: {    FatherToSon  }}</script><style></style>

然后在子组件中通过props的方式接收

<template>  <div class="fatherToSon">    {{fatherToSonData}}  </div></template><script>export default {  name: 'FatherToSon',  props:[    "fatherToSonData"  ]}</script><style scoped></style>
原创粉丝点击