1、父向子传值:
通过props传值
<my-component :msg="msg"></my-component>
//子组件
Vue.component('my-component', {
template: '#broTem',
props: {
'msg':String
},
created() {
console.log(this.msg);
}
});
2、子向父传值:
通过$emit传值
子组件
<template id="broTem">
<div>
<input type="button" value="我是子组件" @click="childMethods">
</div>
</template>
Vue.component('my-component', {
template: '#broTem',
data() {
return {
msg: '子组件的数据'
}
},
methods: {
childMethods: function () {
this.$emit('send-bro-msg', this.msg);
},
},
});
父组件
<div id="app">
<my-component @send-bro-msg="sendBroMsg"></my-component>
</div>
new Vue({
el: '#app',
methods: {
sendBroMsg: function (val) {
console.log(val);
}
},
});
3、父组件调用子组件方法并传值(通过ref传值)
<div id="app">
<input type="button" value="我是父组件" @click="parentMethods">
<my-component ref="myCom"></my-component>
</div>
Vue.component('my-component', {
template: '#broTem',
methods: {
childMethods: function (val) {
console.log(val);
}
},
});
var vm = new Vue({
el: '#app',
data() {
return {
msg: '父组件的数据'
}
},
methods: {
parentMethods: function () {
this.$refs.myCom.childMethods(this.msg);
}
},
});
4、子组件调用父组件方法并传值(通过$parent)
Vue.component('my-component', {
template: '#broTem',
data() {
return {
msg: '子组件的数据'
}
},
methods: {
childMethods: function () {
this.$parent.parentMethods(this.msg);
},
},
});
var vm = new Vue({
el: '#app',
methods: {
parentMethods: function (val) {
console.log(val);//子组件的数据
}
},
});