简单父子组件之间的通信$on和$emit

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Heavy_Dream/article/details/85108342

水一下vue官方文档传送门https://cn.vuejs.org/v2/api/

Demo基于vue build第一个项目上修改

  • 目录结构


  • App.vue文件
<template>
  <div id="app">
    <h1>{{title}}</h1>
    <h2 v-text="title"></h2>
    <h3 v-html="title"></h3>
    <input v-model="newItem" v-on:keyup.enter="addNew">
    <ul>
      <li v-for="item in items" :key="item.label" v-bind:class="{finished: item.isFinished}" v-on:click="toggleFinish(item)">
        {{item.label}}
      </li>
    </ul>
    <p>children tells me: {{childrenWords}}</p>
    <component-a msgFromFather="I am father!" v-on:children-tell-me-something="listenToChildren" v-on:add-todo="addTodo" v-on:delete-todo="deleteTodo"></component-a>
  </div>
</template>

<script>
import Storage from './storage'
import ComponentA from './components/componentA'
// export相当于  new Vue({});
export default {
  // 相当于 date: function(){} 下面是ES6语法
  created () {
    console.log('生命周期')
  },
  data () {
    return {
      title: '<span>渲染HTML</span> this is a todo list',
      items: Storage.fetch(),
      newItem: '',
      childrenWords: ''
    }
  },
  components: { ComponentA },
  watch: {
    items: {
      handler: function (items) {
        Storage.save(items)
      },
      deep: true
    }
  },
  methods: {
    toggleFinish: function (item) {
      console.log(item.isFinished = !item.isFinished)
    },
    addNew: function () {
      this.items.push({
        label: this.newItem,
        isFinished: false
      })
      console.log(this.newItem)
      this.newItem = ''
    },
    listenToChildren: function (msg) {
      // console.log(msg)
      this.childrenWords = msg
    },
    addTodo: function (newTodo) {
      console.log('add')
      console.log(newTodo)
      this.items.push(newTodo)
    },
    deleteTodo: function (todoId) {
      console.log('del')
      this.items = this.items.filter(function (todo) {
        return todo.label !== todoId
      })
    }
  }
}
</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;
}

.finished {
  text-decoration: underline;
}
</style>

  • storage.js文件

const STORAGE_KEY = 'todos-vuejs'
export default {
  fetch: function () {
    return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')
  },
  // es6写法
  save (items) {
    window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
  }
}


  • componentA.vue文件
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>父组件->子组件的props属性:{{msgFromFather}}</h2>
    <input v-model="msgFromChildren"/>
    <button v-on:click="onClickMe">子组件->父组件($emit)</button>
    <button v-on:click="onClickDispatch">子组件->父组件($dispatch)</button>
    <hr>
    <input v-model="newTodoText"/>
    <button v-on:click="addTodo">添加</button>
    <button v-on:click="deleteTodo(newTodoText)">删除</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Hello from component a!',
      msgFromChildren: '',
      newTodoText: ''
    }
  },
  props: ['msgFromFather'],
  methods: {
    onClickMe: function () {
      // console.log(this.msgFromFather)
      this.$emit('children-tell-me-something', this.msgFromChildren)
    },
    onClickDispatch: function () {
      console.log('Vue 1.0升级到2.0中去除了$broadcast和$dispatch方法!')
      // Vue 1.0升级到2.0中去除了$broadcast和$dispatch方法。
      // this.$dispatch('children-tell-me-dispatch', this.msgFromChildren)
    },
    addTodo: function () {
      console.log(this.newTodoText)
      this.$emit('add-todo', { label: this.newTodoText, isFinished: false })
      this.newTodoText = ''
    },
    deleteTodo: function (id) {
      console.log(id)
      this.$emit('delete-todo', id)
      this.newTodoText = ''
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  color: #42b983;
  font-weight: normal;
}
</style>
  • 效果图:

猜你喜欢

转载自blog.csdn.net/Heavy_Dream/article/details/85108342