前言:vue 可以比较灵活的使用 html的片段,并将html的片段进行数据隔离,参数也可以互相传递,组件与组件之间也可以进行数据的交互 合理的使用组件可以避免重复代码或者很方便的调用第三方组件库
vue组件
- 简单实例
- 组件传参实际应用
- 父子组件交互和依赖
 
 
简单实例
注册一个组件
<template id="app1">
    <div>这个是组件的内容</div>
</template>
<script>
import Vue from "vue";
const comp = Vue.extend({
  template: '#app1',             //  id选择器绑定template的内容
});
Vue.component("comp", comp);
</script>
<style scoped>
</style>
导入组件
<template>
<app1/>
</template>
<script>
import app1 from "./index"
export default {
  name: "test1",
  components:{
    app1
  }
}
</script>
<style scoped>
</style>

组件传参实际应用
父传子固定参数传参
使用上主要使用props 属性接收参数,:param 方式传参
test1.vue
<template>
  <div>
    <Comp :num="num1"></Comp>
    <input v-model="num1" type="text"></input>
  </div>
</template>
<script>
import Comp from './Comp'
export default{
  components:{Comp}, // 引用组件
  data(){
    return{
      msg:"1111",
      num1:12311
    }
  }
}
</script>
<style scoped>
</style>
组件
Comp.vue
<template>
  <div>
    <p v-show="count>10&&count<100">这个是数字大于10</p>
    <p v-show="count>100&&count<1000">这个是数字大于100</p>
    <p v-show="count>1000">这个是数字大于1000</p>
  </div>
</template>
<script>
export default{
  name:"Comp",
  props:{
    num:{
      type: Number,
      default:1
    }
    },
  data(){
    return{
      count:this.num
    }
},
  watch:{
    count:{
      handler (oldParam,newParam){
        console.log(newParam);
      }
    }
  },
  methods:{
    test(){
      console.log(this.count)
    },
    created(){
      console.log("创建方法开始了");
    }
  }
}
</script>
<style scoped>
</style>

父子组件交互和依赖
Son.vue
<template>
  <div>我是Son组件
    <p>{{str1}}</p>
  </div>
</template>
<script>
export default {
  name: "Son",
  props:{//props列表
    arr:Array,//定义参数类型
    num:Number,
    str:String,
    str2:{
      type:String,
      default:"我是默认字符串"//定义参数默认值
    },
    func:{
      type:Function,
      required:false//定义参数是否必须值
    },
    obj:{
      type: Object,
      required:false
    }
  },
data(){
  return {
    str1:this.str
  }
},
  created() {
    console.log(this.str);//我是字符串
    console.log(this.str2);//我是默认字符串
    console.log(this.num);//5
    console.log(this.func);//hello(){console.log("hello world!");}
    console.log(this.arr);//[1,2,3]
    console.log(this.obj);//{cont:'我是一个对象'}
    this.func();//hello world!
  }
}
</script>
Father.vue
<template>
  <div class="wrap">
    <div>我是Father组件</div>
    <Son
      str="我是字符串"
      :num=5
      :obj="{cont:'我是一个对象'}"
      :func="()=>{this.hello()}"
      :arr="arr"></Son>
  </div>
</template>
<script>
import Son from './Son'
export default {
  name: "Father",
  components:{  Son  },
  data(){
    return{
      arr:[1,2,3]
    }
  },
  methods:{
    hello(){
      console.log("hello world!")
    }
  },
}
</script>
参考:
 https://blog.csdn.net/qq_44375977/article/details/104884834



















