组件注册的两种写法(根据工作需要选择适合的组件注册写法)
代码如下
全局组件写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全局组件写法</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div class="app">
<button-click></button-click>
</div>
<template id="mbzj">
<button @click="click++">点击次数: {{click}}</button>
</template>
</body>
<script>
//全局注册写法
const app = Vue.createApp();
app.component('button-click', {
template: '#mbzj',
data() {
return {
click: '0',
};
},
});
</script>
</html>
局部组件注册写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>局部组件写法</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div class="app">
<button-click></button-click>
</div>
<template id="mbzj">
<button @click="click++">点击次数: {{click}}</button>
</template>
</body>
<script>
//局部组件写法
const app = Vue.createApp({
//内置组件 component
components: {
buttonClick: {
template: '#mbzj',
data() {
return {
click: 0,
};
},
},
},
});
app.mount('.app');
</script>
</html>
效果
#
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>向子组件传参</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div class="app">
<button-counter name="小明" fraction="75"></button-counter>
<button-counter name="小问" fraction="95"></button-counter>
<button-counter name="小王" fraction="65"></button-counter>
</div>
<template id="counter">
<fieldset>
<p>学生: {{name}}</p>
<p>学分: {{fraction}}</p>
<p>评价:
<span v-if=" fraction>=90 ">优</span>
<span v-else-if=" fraction>=80 && fraction<90">良</span>
<span v-else-if=" fraction>=70 && fraction< 80">中</span>
<span v-else>及格</span>
</p>
</fieldset>
</template>
</body>
<script>
const app = Vue.createApp( );
app.component('button-counter', {
// props: 用数组接收父组件传入的自定义属性做为载体的参数
props: ['name', 'fraction'],
template: '#counter',
});
app.mount('.app');
</script>
</html>
效果