vue 中父子组件传值:props和$emit
1。 父组件向子组件传值:通过props数组:
在vue-cli Login.vue父组件中有AcceptAndRefuse.vue子组件,首先import进子组件hello,然后在components中注册组件,然后在template中使用<hello></hello>组件,制定msg信息
父组件:
//父组件 App.vue <template> <div id="app"> <!-- the router outlet, where all matched components would ber viewed --> <router-link v-bind:to="'/'">Home</router-link> <!-- 为我们创建两个锚点标签,并动态路由,使页面不需要重新加载--> <router-link v-bind:to="'/about'">About</router-link> <router-view></router-view> <hello msg-father="dad无可奉告"></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跳转
给心灵一个纯净空间,让思想,情感,飞扬!