VUE知识整理----一起学习(二)

193 阅读1分钟

子组件通过v-model绑定父组件变量

  • 案例:
父组件:
  <test-model v-model="inputValue"></test-model>
  <span>{{inputValue}}</span>
  data:{
  	inputValue: "inputValue"
  }
子组件:
  <input :value="value" @input="$emit('f1', $event.target.value)"> 1:通过input框的@input进行关联
  <button @click="f2">click me</button> // 方法2:通过事件进行关联
  model:{
    prop:'value', // 对父组件的model变量进行关联
    event:'f1' // 通过event自定义事件传给父组件值
  }
  props:['value']
  methods:{
    f2(){
    	this.$emit('f1', 'xxx');
    }
  }

$ref 获取dom元素,父调用子中的函数

父组件:
  <Uediter ref="ue"></Uediter>
  <h1 ref="h1Ele">这是H1</h1>
  mehods:{
    f1(){
      this.$refs.ue.f2(); // ref绑定组件时可以.f2()表示调用子组件methods中的方法
      console.log(this.$refs.h1Ele.innerText); // this.$refs.ue表示ref对应的Dom元素
    }
  }
子组件:
  mehods:{
      f2(){ console.log(2); }
  }

provide、inject爷孙组件传参

父组件:
  provide(){
    return{
      tabs:this, // 定义传递变量,此处tabs指父组件的实例
      val:'demo'
    }
  }
  methods:{ updateNav(){ console.log(1); } },
子组件:
  inject:['tabs'], // 接收父组件变量
  data(){ return { str:this.val } },
  methods(){
    updateNav(){
    	this.tabs.updateNav(); // this.tabs为父组件传递的变量,当前为访问父组件中的updateNav方法
    }
  }

computed计算属性

new Vue({
  data:{ a:2,b:3 },
  methods:{ f1(){ return (a-0)+(b-0); } }, // 函数没有缓存,每次都会被调用 <input v-model="f1()">
  computed:{
  f2(){ return (a-0)+(b-0); }, // 计算属性有缓存,只有当值被改变时才会调用 <input v-model="f2">
  f3:{
    get(){ return (a-0)+(b-0); }, // 当a,b改变时调用get方法,获取数据给f3
    set(newValue){  // newValue是f3的新值
      // 当f3改变时调用set方法,设置a,b数据,实现双向绑定
      this.a=newValue/2; 
      this.b=newValue/2;
    }
  }
})

watch监听器

  • 使用方法1:在new Vue({...})中
data:{ a:2,b:3 },
watch:{
  a(newValue,oldValue){}, // newValue是a的新值,oldValue为a的旧值
  // 当a发生改变时触发watch.a函数
  //强化监听,可以监听对象的内部变化
  a:{
    deep:true,
    handler:function(newValue,oldValue){}
  }
}
  • 使用方法2:var vm=new Vue({ data:{a:2,b:3}... });
vm.$watch('b',function(newValue,oldValue){ };

过滤器filter

  • 全局过滤器
Vue.filter('contentFilter',(value)=>{ // 第一个参数是过滤器名
	return value.tostring().toUpperCase().replace('tmd','***');
})
使用: 
  {{content | contentFilter}} // content是变量名,contentFilter是过滤器名
  <input type="text" :value="content | contentFilter">
  • 局部过滤器
filters:{
  add(num1,num2,num3){
  	return num1+num3+num3;
  }
}
使用:{{ data1 | filter(data2,data3) }}