VUE2.0和VUE3.0虽然在工程目录结构上存在较大差异,但是具体的代码实现逻辑相同,本文所使用的自定义组件方法,同样适用于VUE2.0。
自定义组件已办存放在VUE工程结构的component文件夹下,新建自定义组件的方式和新建普通vue文件一样,整个VUE代码结构,本文自定义head组件,主要是作为页面的顶部div使用,代码如下:
<template>
<div class="head">
<span>我是子组件span>
div>
template>
<script>
export default {
name: 'Head'
}
script>
<style scoped>
.head{
width: 100%;
height: 100px;
background-color: aqua;
}
style>
自定义组件的调用有两种方式:全局调用和局部调用。
全局调用适用于整个项目工程,局部调用只适用于当前vue文件
全局引用自定义组件需要在main.js中进行申明和引用
VUE3.0,在main.js中引用代码为:
import { createApp } from 'vue'
import App from './App.vue'
import Head from '@/components/head.vue'
const Vue = createApp(App)
Vue.component('Head', Head)
Vue.mount('#app')
VUE2.0,在main.js中引用代码为:
import Vue from 'vue'
import App from './App.vue'
import Head from '@/components/head.vue'
Vue.component('Head', Head)
new Vue({
render: h => h(App)
}).$mount('#app)
父组件在使用全局调用子组件时,需要注意子组件标签要和子组件参数中的
name值
一致,否则会调用失败,代码:
<template>
<div class="home">
<Head>Head>
<span>我是主要部分span>
div>
template>
<script>
export default {
name: 'Home'
}
script>
<style scoped>
.home{
width: 100%;
height: 500px;
background-color: antiquewhite;
}
style>
局部调用需要先引入组件代码import Head from '@/components/head.vue'
,然后在父组件中进行申明,代码为:
<template>
<div class="home">
<Head>Head>
<span>我是主要部分span>
div>
template>
<script>
// 局部引入自定义组件
import Head from '@/components/head.vue'
export default {
name: 'Home',
// 局部引入自定义组件
components: {
Head
}
}
script>
<style scoped>
.home{
width: 100%;
height: 500px;
background-color: antiquewhite;
}
style>
有参子组件的定义和普通带普通变量的VUE文件定义一样
<template>
<div class="head">
<span>{{msg}}span>
div>
template>
<script>
export default {
name: 'Head',
data () {
return {
msg: '我是头部'
}
}
}
script>
<style scoped>
.head{
width: 100%;
height: 200px;
background-color: aqua;
}
style>
在调用有变量的子组件的时,需要在子组件标签中定义指向ref
,即,引用变量的方式为
this.$refs.Head.msg
,同时也可以进行修改,以局部调用组件为例:
<template>
<div class="home">
<Head ref='Head'>Head>
<span>我是主要部分span>
div>
template>
<script>
import Head from '@/components/head.vue'
export default {
name: 'Home',
components: {
Head
},
mounted () {
alert(this.$refs.Head.msg)
this.$refs.Head.msg = '正在调用子组件'
}
}
script>
<style scoped>
.home{
width: 100%;
height: 500px;
background-color: antiquewhite;
}
style>