美文网首页
vue中父子组件传值

vue中父子组件传值

作者: 晚饭总吃撑 | 来源:发表于2020-01-15 09:54 被阅读0次

    vue中父子组件传值是经常使用的场景

    父组件向子组件中传值

    父组件

    <template>
      <div id="app">
        <img alt="Vue logo" src="./assets/logo.png">
        <HelloWorld @changeAge="changeAge" :age="age" :name="name" msg="Welcome to Your Vue.js App"/>
      </div>
    </template>
    
    <script>
    import HelloWorld from './components/HelloWorld.vue'
    
    export default {
      name: 'app',
      data: ()=>{
        return {
          name:"liuhao",
          age:29
        }
      },
      methods:{
        changeAge(){
          this.age++
        }
      },
      components: {
        HelloWorld
      }
    }
    </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>
    

    子组件

    <template>
      <div class="hello">
        <h1>{{ msg }}</h1>
        <h2 class="red">{{ name }}:{{age}}</h2>
        <button @click="changeAge()">修改数据</button>
        <button @click="$emit('changeAge')">修改数据</button>
      </div>
    </template>
    
    <script>
    export default {
      name: 'HelloWorld',
      props: ["msg","name","age"],
      methods:{
        changeAge(){
          this.$parent.changeAge()
        }
      }
    }
    </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;
    }
    .red{
      color:#f3927f
    }
    </style>
    

    父组件向子组件中传值分三步
    1、在父组件中给子组件命名属性,通过该属性向子组件传值
    2、子组件需要事先在props中声明该属性名,这样才能接收父组件传过来的值
    3、在子组件中直接调用属性名,该属性便是父组件传过来的属性值

    子组件传值给父组件有两种方法
    一、第一种
    1、在父组件中定义方法,并通过@+方法名的方式告知子组件传过去的方法名
    2、在子组件中通过$emit(方法名,参数...)调用父组件传过来的方法
    二、第二种
    1、在父组件中定义方法,并通过@+方法名的方式告知子组件传过去的方法名
    2、在子组件中通过this.$parent.方法名()调用

    相关文章

      网友评论

          本文标题:vue中父子组件传值

          本文链接:https://www.haomeiwen.com/subject/lmazactx.html