Vue中的组件,看我就够了

2023-01-10 16:27:50

一、组件的注册

组件注册需要注意的有五点:

1、data要写成函数,并且用return返回一个值,这样不同的调用才能互不影响

2、template后面跟的是飘号,就是Tab上面那个键

3、template后面的内容要写在一个大的div里面,不要分开多个div

4、props后面的是数组,因为有很多个prop

5、要保存成js文件

Vue.component("myson",{
	data(){
		return{
			sonmsg:"hello son"
		}
	},
	template:`
	<div>
		<p>子组件内容</p>
		prop接收到的值:{{sonprop}}
	</div>
	
	`,
	props:["sonprop"],
	methods:{
		sonclick(){
			this.$emit("sonemit",this.sonmsg)
		}
	}
})

二、组件的使用

使用时只要注意一点就好,要先引用vue,再引用子组件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="js/vue.js"></script>
		<script type="text/javascript" src="00-组件-子.js"></script>
	</head>
	<body>
		<div id="app">
			<myson></myson>
		</div>

		<script type="text/javascript">
			var vm = new Vue({
				el:"#app",
				data:{
					parentmsg:"parentmsg to sonprop"
				}
			})
		</script>
	</body>
</html>

三、父传子

父传子比较简单,分成两步

1、在组件里定义prop

props:["sonprop"]

2、使用组件时,用定义的prop绑定父的值

<myson :sonprop="parentmsg"></myson>

父里面的值是这样的

				data:{
					parentmsg:"parentmsg to sonprop"
				}

详细传递过程是这样的,看起来比较复杂,其实就上面说的两步

四、子传父

子组件给父传数值要通过方法来传递,父和子各定义一个方法,然后用一个中间方法来连接,记住这个中间方法的使用就行了,步骤详细分解开挺多的

1、在子组件的template的button里使用一个点击事件

<button @click="sonclick">按钮</button>

2、在子组件里定义上面使用的方法,触发一个中间方法并传递数据

		sonclick(){
			this.$emit("sonemit",this.sonmsg)
		}

3、父使用子组件时,用中间方法绑定自己的方法

<myson @sonemit="parentclick"></myson>

4、在父的方法里接收数据,这里p可以写成任意字符

        parentclick(p){
			vm.parentmsg=p;
		}

 详细代码图

运行效果

五、插槽

1、加入插槽,插槽就是在组件里留一个空位,使用组件时可以插入任意东西

在子组件某个位置定义:<slot></slot>

使用组件时就可以在该位置添加任意标签

2、加入多个插槽时,要为每个插槽命名,使用时每个slot要放在一个template里面

定义多个插槽

	template:`
	<div>
		<p>子组件内容:{{sonmsg}}</p>
		<p>分隔线111111111111111</p>
		<slot name="a1"></slot>
		<p>分隔线2222222</p>
		<slot name="a2"></slot>
		<p>分隔线333333333</p>
	</div>
	
	`,

使用多个插槽,一个template放一个slot

                <template slot="a1">
					<button>按钮a1</button>
				</template>
				<template slot="a2">
					<button>按钮a2</button>
				</template>

六、子组件给插槽传值

1、在子组件template里定义中间数据emitmsg,名字可以随便

<slot name="a1" :emitmsg="sonmsg"></slot>

2、在父组件里用res接收,不管是多少个子组件,都是用res接收,res是结果集,如果有多个slot的话,数据都会在里面

				<template slot="a1" slot-scope="res">
					{{res.emitmsg}}
				</template>

代码展示

 显示效果:


今天看了下数据,突然多了70个粉丝,嘿嘿,谁帮我刷的,谢谢

然后顺手点了个CSDN弹出的调查,本来想顺手做下的,结果看了第一项就关掉了,原来我啥也不会

  • 作者:youngcave2
  • 原文链接:https://blog.csdn.net/yougcave/article/details/120912882
    更新时间:2023-01-10 16:27:50