兄弟组件之间的传值vue
用vue实例传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<componenta></componenta>
<componentb></componentb>
</div>
<script src="../vue.js"></script>
<script>
var bus=new Vue();//新建一个实例
Vue.component('componenta', {
template: `
<div>
<h1>这是组件</h1>
<button @click="send">发送</button>
</div>
`,
data: function() {
return {
msg: "我是组件A的值,要传给B"
}
},
methods:{
send(){
bus.$emit('sendEvent',this.msg);
}
}
})
Vue.component('componentb',{
template:`
<div>
<h1>这是组件B</h1>
<p>{{txt}}</p>
</div>
`,
data:function(){
return{
txt:""
}
},
mounted() {
/* var that=this;
bus.$on('sendEvent',function(msga){
that.txt=msga;
}) */
//方法二:箭头函数 this指向不会发生改变
bus.$on('sendEvent',(msga)=>{
this.txt=msga;
})//Es6
}
})
new Vue({
el: "#app"
})
</script>
</body>
</html>
Vue自定义指令
1、自定义指令:使用Vue.directive(id,definition)注册全局自定义指令,使用组件的directives选项注册局部自定义指令。
2、钩子函数:
指令定义函数提供了几个钩子函数(可选):
bind:只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
inserted:被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
(来自百度搜索)
update:第一次是紧跟在 bind 之后调用,获得的参数是绑定的初始值,之后被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新。
等
3、钩子函数的参数:(el, binding)
el:指令所绑定的元素,可以用来直接操作 DOM 。(常用)
binding:一个对象,包含以下属性
name:指令名,不包含v-的前缀;
value:指令的绑定值;例如:v-my-directive=“1+1”,value的值是2;
等
以下有四个有案列
1,用Vue自定义指令给input框被选中
2,用Vue自定义指令加背景颜色
3,用Vue自定义指令刷新随机改变背景颜色
4,Vue.use的用法
自定义指令的第二用处是用于集成第三方插件。用vue.use
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app" v-chg>//绑定自定义插件
<input type="text" v-focus />
<p v-color>hahlhdkshaahd</p>
</div>
<script src="../vue.js"></script>
<script src="plugin.js"></script>
<script>
Vue.directive('focus',{
inserted(el){
el.focus();
}
})
Vue.directive('color',{
inserted(el){
var num=(Math.random()*1000000).toFixed(0);
el.style.background='#'+num;
}
})
Vue.use(myPlugin);//Vue.use的用法
new Vue({
el:"#app",
})
</script>
</body>
</html>
plugin.js代码
var myPlugin={};
myPlugin.install=function(){
Vue.directive('chg',{
inserted(el){
el.style="width:1600px;height:100px;background:#e6caff";
}
})
}