关于vue父子组件传值问题

今看到一篇关于vue传值的文章,遂记下。共勉之!

/*
*  父组件界面写法
*/
<template>
     <div  id="home">

         <child  :sendDataToChid="words" 
           :sendSecondData="moreWords"
           @fromSon="fromSon">
         </child>
         <p>{{fromSonData}}</p>
</div> </template> <script> import Child from '@/components/child.vue' export default { name:'home', data(){ return{ words:'从父组件过去的数据哦', moreWords:'多个数据也可以传递哦', fromSonData:'现在啥都没有哦', } },
components:{
Child
}, methods:{
//接收从子组件传递过来的数据 fromSon(data){ this.fromSonData = data; } } } </script>
<style>
/**这里写样式哦**/
</style>

/*
*  子组件界面写法
*/
<template>
    <div  id="child">
         <p>{{sendDataToChid}}</p>
         <p>{{sendSecondData}}</p>
         <button @click="sendDataToFather">
           点击按钮就可以向父组件 传递值了
         </button>
    </div>
</template>

<script>
    export default{
        name:'child',
        props:['sendDataToChid','sendSecondData'],
        data(){
            return(){
            }
        },
        methods:{
           sendDataToFather(){
              let greetWords = 'hello world!';
              this.$emit('fromSon',greetWords )
           }
        }
    }
</script>
<style>
/**这里写样式哦**/
</style>

父组件向子组件传值方式就是通过  props 属性,子组件通过 props 属性接收从父组件传过来的值,而父组件传值的时候使用 v-bind 将子组件中预留的变量名绑定为  data 里面的数据即可。

子组件向父组件传值方式就是用了  this.$emit 来遍历  fromSon 事件 ,首先用按钮来触发  sendDataToFather  事件,在  sendDataToFather 中用 this.$emit 来遍历 fromSon 事件,最后返回  this.fromSonData 值。

简短总结:

子组件中需要以某种方式 例如点击事件的方法来触发一个自定义事件,

将需要传递的值作为 $emit 的第二个参数,该值将作为实参传递给响应自定义事件的方法,

在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听。

 。

 。

 。

第二弹来了

就是,父组件需要点击某个按钮触发事件后,再改变子组件的界面相关内容。代码如下:

给父组件写一个ref属性,父组件可以通过ref拿到子组件中的数据和方法,这样在父组件中就可以触发子组件的事件了。父组件向子组件传参通过prop属性。
父组件:
<div>
<children ref="children" :content="content"></children>
<button @click="handleSubmit">点击</button>
</div>
//js
handleSubmit(){
this.$refs.children.updateList();
}
子组件:
<template>
<div>children</div>
</template>
//js
export default{
props:{
content:{
type:String,
}
},
data(){
return{
text:'hello world'
}
},
methods:{
updateList(){
console.log('hello world');
}
}
}
数据传递用prop,事件调用用ref。
原文地址:https://www.cnblogs.com/sunnyeve/p/11385277.html