08. 组件

2022-10-12 15:08:07发布
64

定义一个组件B.vue,并且在页面A.vue上使用

组件B.vue

<template>
  <div>
    <span @click="clickMe">{{name}}</span>
  </div>
</template>
<script>
export default {
  data(){
    return{
      name : 'tom'
    }
  },
  methods:{
    clickMe(){
      alert('you click me');
    }
  },
  created() {
    console.log('created');
  },
}
</script>

页面A.vue

<template>
  <div>
    <B />
  </div>
</template>
<script>
import B from "./B.vue";
export default {
  components:{
    B
  }
}
</script>

使用组件的步骤 :

1、import

2、components注册

3、在template使用


父组件传递数据给子组件

使用v-bind和props实现。例子 :

父组件

<template>
  <div>
    <test :config="config" :list="list" :model="model" />
  </div>
</template>
<script>
import test from "@/components/test";
export default {
  components: {
    test,
  },
  data() {
    return {
      config: {
        type: 1,
        open: true,
      },
      list: [1, 2, 3, 4],
      model: 101,
    };
  },
};
</script>

子组件

<template>
  <div>test</div>
</template>
<script>
export default {
  props: {
    config: {
      type: Object,
      default: () => {
        return {};
      },
    },
    list: {
      type: Array,
      default: () => [],
    },
    model: {
      type: Number,
      default: 100,
    },
  },
  mounted() {
    console.log(this.config);
    console.log(this.list);
    console.log(this.model);
  },
};
</script>


子组件传递数据给父组件

使用v-on和$emit实现。例子:

子组件

<template>
  <div>test</div>
</template>
<script>
export default {
  mounted() {
    this.$emit("updata", {
      name: "tom",
      age: 12,
    });
  },
};
</script>

父组件

<template>
  <div>
    <test @updata="getData" />
  </div>
</template>
<script>
import test from "@/components/test";
export default {
  components: {
    test,
  },
  methods: {
    getData(data) {
      console.log(data);
    },
  },
};
</script>


兄弟组件传值

当组件的嵌套比较深,或者2个组件不是父子关系需要互相发送数据时,可以使用下面的方法。

1、新建一个文件,编写以下内容

import Vue from 'vue';
export default new Vue();

2、编写2个组件,然后引入同一个vue文件中

<template>
  <div class="hello">
    <testA/>
    <testB/>
  </div>
</template>
<script>
import testA from './testA';
import testB from './testB';
export default {
  components : {
    testA,
    testB
  },
  data () {
    return {
      
    }
  }
}
</script>
<style scoped>
</style>

3、现在testA组件向testB组件发送数据

<template>
  <div class="testA">
    testA
  </div>
</template>
 
<script>
import hub from '../config';
export default {
  data () {
    return {
      msg : 'abc'
    }
  },
  mounted(){
    hub.$emit('msg',this.msg); //testA用$emit发送数据
  }
}
</script>
<style scoped>
</style>

4、testB接收数据

<template>
  <div class="b">
    b
  </div>
</template>
 
<script>
import hub from '../config';
export default {
  data () {
    return {
      
    }
  },
  created(){
    hub.$on('msg',(val)=>{ //testB用on事件接受数据
      alert(val) 
    });
  }
}
</script>
<style scoped>
</style>

tips:这里需要注意的是,一定要先触发on事件在执行emit事件,所以testA的emit事件写在了mounted钩子函数里,testB的on事件则写在了created函数里。