vue 中父子组件传值:props和$emit
更新-----------
1 父组件向子组件传值:通过props数组:
在vue-cli Login.vue父组件中有AcceptAndRefuse.vue子组件,首先import进子组件hello,然后在components中注册组件,然后在template中使用<hello></hello>组件,制定msg信息
//父组件 App.vue
<template>
<div ></hello>
</div>
</template>
<script>
import hello from './components/hello'
export default {
name: 'app',
components:{
hello
}
}
</script>
<!-- styling for the component -->
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
//子组件./components/Hello.vue
//通过props接收信息
<template>
<div class="hello">
<p>{{msgFather}}</p>
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
}
},
props:['msgFather']
}
</script>
<style scoped>
</style>
子组件即可收到通信
传进来的数据是mes-father, vue转化成mesFather, 在js 里面写mesFather
http://www.jianshu.com/p/2670ca096cf8
2 子组件向父组件传值:自定义事件,this.$emit,发送信息,在父组件中
子组件:
<template> <div class="hello"> <!-- 添加一个input输入框 添加keypress事件--> <input type="text" v-model="inputValue" @keypress.enter="enter"> <p>{{mes}}</p> </div> </template> <script> export default { props:['mes'], // 添加data, 用户输入绑定到inputValue变量,从而获取用户输入 data: function () { return { inputValue: '' } }, methods: { enter () { this.$emit("sendiptVal", this.inputValue) //子组件发射自定义事件sendiptVal 并携带要传递给父组件的值, // 如果要传递给父组件很多值,这些值要作为参数依次列出 如 this.$emit('valueUp', this.inputValue, this.mesFather); } } } </script>
父组件:
<template> <div>
<p> father</p>
<accept-and-refuse :mes=loginJson.animal @sendiptVal='showChildMsg'></accept-and-refuse>
</div> </template> <script> import AcceptAndRefuse from '@/components/public/AcceptAndRefuse' export default { data() { return { message:'hello message', loginJson:{ "animal":"dog" } }, mounted(){ }, methods: { components:{ AcceptAndRefuse } } </script> <style> </style>
在vue组件中,import子组件,components中注册,template中使用,router跳转