今天想起一直没有记录父组件与子组件的传参问题,这在项目中一直用到。
父向子组件传参
Index.vue父组件中
<component-a :msgfromfa="(positionnow)"></component-a>
import componentA from './components/componentA'
export default{
name:'Index',
data(){
return{
positionnow:''
}
}
}
componentA.vue子组件中
<p>{{msgfromfa}}</p>
export default{
props:['msgfromfa']
}
子向父组件传参
Index.vue父组件中
<p>Do you like me? {{childWords}}</p>
<component-a v-on:child-say="listenToMyBoy"></component-a>
import componentA from './components/componentA'
export default {
new Vue({
data: function () {
return {
childWords: ""
}
},
components: {
componentA
},
methods: {
listenToMyBoy: function (msg){
this.childWords = msg
}
}
})
}
componentA.vue子组件中
<button v-on:click="onClickMe">like!</button>
import componentA from './components/componentA'
export default {
data: function () {
return {
msg: 'I like you!'
}
},
methods: {
onClickMe: function(){
this.$emit('child-say',this.msg);
}
}
}