vue.js

来源:互联网 发布:西门子pdm软件下载 编辑:程序博客网 时间:2024/05/22 06:17

1、自定义事件

方法一:
Vue实例实现了一个自定义事件接口,用于在组件树中通信。这个事件系统独立于原生DOM事件,用法也不同。

每个Vue实例都是一个事件触发器:

  • 使用$on()监听事件
  • 使用$emit()在它上面触发事件
  • 使用$dispatch()派发事件,事件沿着父链冒泡
  • 使用$broadcast广播事件,事件向下传导给所有的后代
    注意:不同于DOM事件,Vue事件在冒泡过程中第一次触发回调之后自动停止冒泡,除非回调明确返回true。

store.js代码如下:

const STORAGE_KEY = 'todos-vue.js'export default{    fetch(){        return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]')    },    save(items){        window.localStorage.setItem(STORAGE_KEY,JSON.stringify(items));    }}

App.vue代码如下:

<template>  <div id="app">    <h1 v-text="title"></h1>    <input v-model="newItem" v-on:keyup.enter="addNew"/>    <ul>      <li v-for="item in items" v-bind:class="{finished:item.isFinished}" v-on:click='toogleFinish(item)'>        {{item.label}}      </li>    </ul>    <!-- 使用组件,注意驼峰命名法转化成短线 -->    <!-- 向自组件传数据 -->    <!-- 自定义事件 -->    <p>child tells me:{{childWords}}</p>    <Component-a msgfromfather='you die!'v-on:child-tell-me-something='listenToMyBoy'></Component-a>  </div></template><script>import Store from './store'import ComponentA from './components/componentA'    //该组件会被加载到该页面export default {  name: 'app',  data () {    return {      title: 'this is a todo list',      items:Store.fetch(),      newItem:'',      childWords:''    }  },  components:{  //注册组件    ComponentA  },  watch:{      items:{        handler(items){     //经过变化的数组会作为第一个参数传入          Store.save(items)        },        deep:true       //深度复制      }  },  methods:{    toogleFinish(item){      item.isFinished = !item.isFinished    },    addNew(){      this.items.push({        label:this.newItem,        isFinished:false,      })      this.newItem = ''    },    listenToMyBoy(msg){      this.childWords = msg;    }  }}</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>

componentA.vue代码如下:

<template>  <div class="hello">    <h1>{{msg}}</h1>    <h2>{{msgfromfather}}</h2>    <button v-on:click="onClickMe">Click!</button>  </div></template><<script>export default {  data(){      return{          msg:'Hello form component a'      }  },  props:['msgfromfather'],//自组件接收数据  methods:{      onClickMe(){          //console.log(this.msgfromfather);          this.$emit('child-tell-me-something',this.msg);      }  }}</script><style scoped></style>

效果如下:
这里写图片描述

原创粉丝点击