标签:method port eve script mod turn import 参数 name
1 父组件向子组件传值:通过props数组:
//父组件 App.vue <template> <div id="app"> <hello mes-father="爸爸无可奉告"></hello> </div> </template>
//子组件Hello.vue <template> <div class="hello"> <p>{{mesFather}}</p> </div> </template> <script> export default { props:[‘mesFather‘] } </script>
子组件即可收到通信
传进来的数据是mes-father, vue转化成mesFather, 在js 里面写mesFather
2 子组件向父组件传值:自定义事件
子组件:
<template>
  <div class="hello">
    <!-- 添加一个input输入框 添加keypress事件-->
    <input type="text" v-model="inputValue" @keypress.enter="enter">
    <p>{{mesFather}}</p>
  </div>
</template>
<script>
export default {
  props:[‘mesFather‘],
  // 添加data, 用户输入绑定到inputValue变量,从而获取用户输入
  data: function () {
    return {
      inputValue: ‘‘  
    }
  },
  methods: {
    enter () {
      this.$emit("sendiptVal", this.inputValue) 
      //子组件发射自定义事件sendiptVal 并携带要传递给父组件的值,
      // 如果要传递给父组件很多值,这些值要作为参数依次列出 如 this.$emit(‘valueUp‘, this.inputValue, this.mesFather); 
    }
  }
}
</script>
父组件:
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <!-- 添加自定义事件valueUp -->
    <hello mes-father="message from father" @valueUp="recieve"></hello>
    <!-- p元素,用于展示子组件传递过来的数据 -->
    <p>子组件传递过来的数据 {{childMes}}</p>
  </div>
</template>
<script>
import Hello from ‘./components/Hello‘
export default {
  name: ‘app‘,
  components: {
    Hello
  },
  // 添加data
  data: function () {
    return {
      childMes:‘‘
    }
  },
  // 添加methods,自定义事件valueUp的事件处理函数recieve
  methods: {
    recieve: function(mes) { // recieve 事件需要设置参数,这些参数就是子组件传递过来的数据,因此,参数的个数,也要和子元素传递过来的一致。
      this.childMes = mes;
    }
  }
}
</script>
标签:method port eve script mod turn import 参数 name
原文地址:http://www.cnblogs.com/rlann/p/7163045.html