vue 父子组件相互传参

vue 父子组件相互传参,第1张

vue 父子组件相互传参

转自https://blog.csdn.net/u011175079/article/details/79161029

子组件:

<template>
<div>
<div>{{count}}</div>
<div v-for="(item, index) in list">{{item}}</div>
<button v-on:click="sendMsg">向父组件传参</button> <!-- 这里用简单的绑定方法触发传参-->
</div>
</template> <script>
export default {
name: 'main_header',
props: ['count', 'list'],
methods: {
sendMsg: function () { //传参方法
this.$emit('headCallBack', '子组件的参数内容'); //第一个参数是父组件中v-on绑定的自定义回调方法,第二个参数为传递的参数
}
}
};
</script> <style>
</style>

父组件:

<template>
<div id="app">
<img src="./assets/logo.png">
<div>子组件传过来的内容:{{msg}}</div>
<mainHeader :count="count" :list="list" v-on:headCallBack="headCall"></mainHeader> <!--通过v-on绑定方法,headCallBack为子组件中$emit()中第一个参数,headCall为回调方法,参数就传入这个方法中,看下面的方法-->
<router-view/>
</div>
</template> <script>
import mainHead from './components/header/main_header';
var data = {
list: ['java', 'html', 'css', 'js']
};
export default {
name: 'app',
data: function () {
return {
count: 0,
list: data.list,
msg: ''
};
},
components: {
mainHeader: mainHead
},
methods: {
addCount: function () {
let _this = this;
setInterval(function () { _this.count++; }, 1000);
},
headCall: function (msg) { //回调方法,接收子组件传的参数
this.msg = msg;
}
},
mounted: function () {
this.$nextTick(function () {
this.addCount();
});
}
};
</script>

总结一下:

子组件向父组件传参

  • 子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
  • 将父组件中v-on:后事件名称作为$emit的第一个参数,需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
  • 在父组件中注册子组件,并在子组件标签上绑定对自定义事件的监听

父组件向子组件传参

  • 父组件定义属性值
  • 子组件先声明对应的props:['属性名'],之后使用此属性时,可向使用自身元素一样使用父组件的元素

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/589118.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存