时间:2021-02-11 11:18:24 | 栏目:vue | 点击:次
方法写在methods中
v-on:click="run()"
@click="run()"
方法获取data中的数据通过this.数据获取
方法设置data中的数据通过this.数据=''设置
例如通过this.list=[1,2,3],设置list的值,让页面出循环list
可通过 @click="run('123')",将值传到方法中
可通过 @click="run($event)",将事件对象传到方法中,然后根据事件对象的e.srcElement设置点击标签的属性,也可以通过e.srcElement.dataset获取自定义属性
<template> <div id="app"> {{msg}} <button @click="run()">@click事件触发</button> <button v-on:click="runvon()">v-on:click事件触发</button> <button @click="getMsg()">获取data.msg</button> <button v-on:click="setMsg()">设置data.msg</button> <ul> <li v-for="item in list">{{item}}</li> </ul> <button @click="setList()">设置List的值</button> <button @click="sendData('123')">方法传值</button> <button v-on:click="sendEvent($event)">传递事件对象</button> <button @click="sendEventSet($event)">传递事件对象,并设置背景色</button> <button data-a="啦啦啦" @click="sendEventData($event)">传递事件对象,并获取自定义属性</button> </div> </template> <script> export default { name: 'app', data () { return { msg: '123', list:[] } }, methods:{ run(){ alert("@click事件触发") }, runvon(){ alert("v-on:click事件触发") }, getMsg(){ alert("我获取到了msg"+this.msg); }, setMsg(){ this.msg="我是设置后的值" }, setList(){ for(var i = 0 ; i < 10 ; i++){ this.list.push(i) } }, sendData(a){ alert("穿过来的值是:"+a) }, sendEvent(e){ console.log(e); }, sendEventSet(e){ e.srcElement.style.background="red"; }, sendEventData(e){ alert(e.srcElement.dataset.a) } } } </script> <style lang="scss"> </style>
补充知识:Vue 兄弟组件通过事件广播传递数据
非父子组件传值
通过事件广播实现非父子组件传值
1.新建js,引入并实例化Vue
import Vue from 'vue' var VueEvent = new Vue(); export default VueEvent;
2.子组件A中引入VueEvent,并广播事件
import VueEvent from '../model/VueEvent.js'
VueEvent.$emit('to-news',this.msg);
3.子组件B中引入VueEvent,并监听事件
import VueEvent from '../model/VueEvent.js'
VueEvent.$on('to-news',data=>{console.log(data);});
示例代码
import Vue from 'vue' var VueEvent = new Vue(); export default VueEvent;
<template> <div id="home"> <button @click="sendMsg()">我来触发事件</button> </div> </template> <script> import VueEvent from "../models/VueEvent.js"; export default { data() { return { msg: "我是Home的msg" }; }, methods: { sendMsg() { VueEvent.$emit("tonews", this.msg); } } }; </script> <style> </style>
<template> <div id="news"> 我来接受事件--{{msg}} </div> </template> <script> import VueEvent from "../models/VueEvent.js"; export default { data() { return { msg: "我是News的msg" }; }, mounted() { VueEvent.$on("tonews", res => { this.msg = res; }); } }; </script> <style> </style>
<template> <div id="app"> <v-home></v-home> <hr /> <v-news></v-news> </div> </template> <script> import Home from "./components/Home.vue"; import News from "./components/News.vue"; export default { name: "app", data() { return { msg: "Welcome to Your Vue.js App" }; }, components: { "v-home": Home, "v-news": News } }; </script> <style lang="scss"> </style>