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>
效果如下:
阅读全文
0 0
- vue.js
- vue.js
- vue.js
- Vue.js
- vue.js
- Vue.js
- vue.js
- vue.js
- vue.js
- Vue.js
- vue.js
- Vue.js
- Vue.js
- Vue.js
- Vue.js
- Vue.js
- Vue.js
- vue.js
- 支持向量机(SVM)的分析及python实现
- 贾跃亭卸任乐视网董事长 出任乐视汽车生态全球董事长
- 中科院院士谭铁牛:模式识别研究的回顾与展望 | CCF-GAIR 2017
- 小米二季度手机出货创纪录,雷军定了“一个亿”的小目标
- 惊呆!人类药丸?今天一大波机器人占领了深圳喜来登六楼 | CCF-GAIR 2017
- vue.js
- Python变量和数据类型
- 【实践】电路结构初探
- Angular 4入门教程系列:5:Tour Of Heroes之组件复用
- 百度金融高级科学家吴健民:智慧金融助力金融机构迎接 AI 新时代 | CCF-GAIR 2017
- 现场花絮:最酷的机器人,最火的会场,还有最牛的演讲者 | CCF-GAIR 2017
- Ubuntu下安装VMware Tools的详细过程
- cms02---basic-Hibernate
- 把书读薄:大型网站技术架构-核心原理与案例分析(第四篇 架构师)