首页 > 代码库 > vue子父组件的通信

vue子父组件的通信

1、父组件像子组件传值

a、app.vue父组件

<template>
  <div id="app">
    <h1>{{title}}</h1>
    <h1 v-text="title"></h1>
    <h1 v-html="title"></h1>
    <input type="text" v-model="newItem" v-on:keyup.enter="addNew">
    <ul>
        <li v-for="item in items" v-bind:class="{finished:item.isFinished}" v-on:click="toggleFinish(item)">
        {{item.label}}
        </li>
    </ul>
  <componentA msgfromfather=‘hongMaJu‘></componentA>
   <component-a></component-a>
  </div>
</template>

<script>
import Store from ./Store
import componentA from ./components/componentA
//console.log(Store)
export default {
  
   data () {
    return {
      title: <span>?</span>this is a todolist,
      items:Store.fetch(),
      // items:[
      //     {
      //       label:‘coding‘,
      //       isFinished:false
  
      //     },
      //     {
      //       label:‘walking‘,
      //       isFinished:true
  
      //     }
      // ],
      newItem:‘‘
    }
  },
  components:{componentA},
  watch:{
    items:{
      handler:function(items){
        // console.log(val,oldVal)
         // console.log(items);

        Store.save(items);
         // console.log(items);

      }
    },
    deep:true
  },
  methods:{
    toggleFinish:function(item){
      // console.log(item);
      item.isFinished=!item.isFinished;
      console.log(this.items);
    },
    addNew:function(){
      // this.newItem;
      // console.log(this.newItem);
      this.items.push({
        label:this.newItem,
        isFinished:false
      })
      this.newItem=‘‘;
    }
  }
}
</script>

<style>
.finished{
  text-decoration:underline;
}
#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>

b、componentA.vue子组件

 <<template>    
<div class="hello">
    <h1>{{msg}}</h1>
    <button v-on:click="onClickMe">click me!</button>
    <h1>{{msgfromfather}}</h1>
</div>
 </template>
 <script>
     export    default{
         data:function(){
             return{
                 msg:hello from component a
             }
         },
         props:[msgfromfather],
         methods:{
             onClickMe:function(){
console.log(this.msgfromfather);
             }
         }
     }

 </script>

 <style>
h1{
    color: #42b983;
}
 </style>

c、效果

技术分享

 

vue子父组件的通信