组件传值
组件关系:
1、父子关系
2、兄弟关系
组件传值:
1、父传子
当子组件在父组件中当做标签使用时,给当前子组件绑定一个自定义属性,值为需要传递的数据。
<v-child name="hello" :name1="title" ></v-child>
在子组件内部通过props属性来进行接收属性名,接收方式为数组。
props:['name','name1']
2、子传父
给子组件的按钮注册点击事件,点击事件中,$emit(),第一个参数为函数名,第二个参数为传递的参数
<button @click="setUser">子组件向父组件传值</button>
setUser:function(){
// 点击按钮时,通过emit传userinfo
// 组件的父级,可以通过事假绑定的方式,接收到emit函数所触发的事件
this.$emit('transfer',this.userinfo);
}
在子组件标签中,写对应接收函数,父组件定义接收函数,参数即为传过来的值。
<v-child @transfer="getUser"></v-child>
getUser:function(msg){
this.info = msg;
}
3、非父子
利用第三方对象,调用emit进行事件数据推送,on接收
var vm = new Vue({});
methods: {
send(){
vm.$emit("isa",this.info);
}
}
mounted() {
vm.$on("isa",(data)=>{
this.infoa = data;
});
}
组件操作
利用ref和$refs方法,获取dom元素
<div id="app">
<h2>组件操作</h2>
<button ref="getH" @click="get()">获取元素h2</button>
</div>
methods: {
get(){
console.log(this.$refs.getH);
}
}
父组件操作子组件
在子组件标签添加ref属性
<v-child ref="child"></v-child>
在父组件的点击方法中
this.$refs.child
获取到子组件的VueComponent
// 打印子组件
console.log(this.$refs.getChild);
// 打印子组件的数据
console.log(this.$refs.getChild.title);
// 调用子组件的方法
this.$refs.getChild.tap();
子组件操作父组件
只要是嵌套关系,无需加其他东西,直接this.$parent得到直接父级的组件
<button @click="getParent()">得到父组件</button>
getParent(){
console.log(this.$parent);
}
$nextTick
$nextTick
,保证实时得到最新的dom元素
mounted() {
this.title = 'hi';
// 得到的是之前的数据
// console.log(this.$refs.tit.innerHTML);
// 如果得不到最新操作的DOM树
// 就把代码放到$nextTick函数中
this.$nextTick(()=>{
// 得到的是hi
console.log(this.$refs.tit.innerHTML);
})
}
自定义指令
全局自定义指令
Vue.directive('color',{
// 这个元素插入父元素的时候执行的操作
inserted:function(el){
// el 等于 绑定了该指令的dom
el.style.color='blue';
}
})
局部自定义指令
var app1 = new Vue({
el: '#inner',
directives: {
'background':{
bind(el,a){
el.style.backgroundColor = 'yellow';
// 第二个参数,包含name rawName modifiers def等
console.log(a);
}
}
}
});
bind 和 inserted 都只会触发一次
update 和 componentUpdated 可以改变
简写形式:
Vue.directive('color',function(el,binding){
el.style.color=binding.value;
})
directives: {
'background':function(el,a){
el.style.backgroundColor = 'yellow';
// 第二个参数,包含name rawName modifiers def等
console.log(a);
}
}