Vue组件通信方式1-props

2020-06-03  本文已影响0人  理子
显示父组件传来的值 弹窗,显示子组件的值

父组件 App.vue

<template>
  <div id="app">
    <!-- 父组件给子组件props传值 -->
    <!-- props组件传值除了字符串 其他的必须动态绑定 -->
    <Props name="a" :age="18" :person="p" :alertInfo="sayHello"/>
  </div>
</template>

<script>
import Props from './components/Props.vue';

export default {
  name: 'App',
  components: {
    Props,
  },
  data(){
    return{
      p:{
        name:'yaya',
        age:100
      }
    }
  },
  methods:{
    // 子组件有形参 显示子组件里的值(模型)
    sayHello(name, age){
      alert(`${age}的${name}say hello!`);
    },

    // 子组件没有形参
    // sayHello(){
    //   alert('Say Hello');
    // },

  }
}
</script>

<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/Props.vue

<template>
  <div class="hello">
    <p>name: {{name}} </p>
    <p>age: {{age}}</p>
    <p>{{person}}</p>
    <button @click="alertInfo('理子',18)">点我hello</button>
  </div>
</template>

<script>
export default {
  name: 'Props',
  //简单的接收方式
  // props: ['name', 'age']
  /*
  props: {
    name: String,
    age: Number,
    person: Object,
    logPerson: Function
  }
  */

  //带校验&默认值的接收方式
  props: {
    name: {type: String, required: true, default: '撩课'},
    age:  {type: Number, required: false, default: 20},
    person: Object,
    alertInfo: Function
  },
  
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
上一篇下一篇

猜你喜欢

热点阅读