码迷,mamicode.com
首页 > 其他好文 > 详细

vue子父组件的通信

时间:2017-05-12 23:07:42      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:new   export   -o   console   put   class   alias   line   this   

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子父组件的通信

标签:new   export   -o   console   put   class   alias   line   this   

原文地址:http://www.cnblogs.com/hongmaju/p/6847494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!