Vue中父子组件通信

添加stylus-loader

1
npm install stylus-loader css-loader style-loader --save-dev

父子组件代码

./src/App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<template>
<div id="app">
<child v-bind:message="parentMsg" v-on:listenToChildEvent="showMsgFromChild"></child>
</div>
</template>

<script>
import child from './components/Child'
export default {
name: 'app',
data(){
return{
parentMsg:"hello,child"
}
},
methods:{
showMsgFromChild:function(data){
console.log(data);
}
},
components:{
child
}
}
</script>

<style lang="stylus" scoped>
div
font-size 500px
color green
</style>

./src/components/Child.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div id="app">
<h2>child子组件部分</h2>
<p>{{message}}</p>
<button v-on:click="sendMsgToParent">向父组件传值</button>
</div>
</template>

<script>
export default {
props:["message"],
methods:{
sendMsgToParent: function () {
this.$emit("listenToChildEvent","this message is from child");
}
}
}
</script>

<style>

</style>

参考

关注我的微信公众号[李一二],即时看更多的文章