vue组件注册
- 全局组件:注册在vue实例上的 使用
实例名.component('模板名称',{template:'模板内容'...})
- 局部组件:注册在vue实例选项上的 在内部使用
components
定义
<div id="app">
<blog-text></blog-text>
</div>
<template id="box">
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>婚否</th>
</tr>
</thead>
<tbody>
<tr v-for="(v,k) of shuju">
<td>{{v.name}}</td>
<td>{{v.age}}</td>
<td v-if="v.hun===true">已婚</td>
<td v-if="v.hun===false">未婚</td>
</tr>
</tbody>
</table>
</template>
//全局组件:注册在VUE实例上的
const app = Vue.createApp();
app.component("blog-text", {
template: "#box",
data() {
return {
shuju: [
{
name: "小王",
age: 18,
hun: false,
},
{
name: "小刘",
age: 20,
hun: false,
},
{
name: "小张",
age: 25,
hun: true,
},
],
};
},
});
//局部组件:注册在VUE实例内部选项内的
const app = Vue.createApp({
components: {
blogText: {
template: "#box",
data() {
return {
shuju: [
{
name: "小王",
age: 18,
hun: false,
},
{
name: "小刘",
age: 20,
hun: false,
},
{
name: "小张",
age: 25,
hun: true,
},
],
};
},
},
},
});
app.mount("#app");
组件传值
- 父组件->子组件传值
<div class="app">
<blog-text username="admin" email="admin@qq.com"></blog-text>
</div>
<template id="box">用户名:{{username}}:邮箱:{{email}}</template>
const app = Vue.createApp();
app.component("blog-text", {
//通过props接收组件传过来的值
props: ["username", "email"],
template: "#box",
});
app.mount(".app");
- 子组件->父组件传值/监听子组件事件
<div class="app">
<blog-text @panduan="review"></blog-text>
</div>
<template id="box">
<button @click="cont++">点赞:{{cont}}</button>
<button @click="$emit('panduan',this.cont)">评价</button>
</template>
const app = Vue.createApp({
methods: {
review(e) {
// console.log(e);
if (e >= 10) {
// console.log(111);
alert("谢谢您的评价");
}
},
},
});
app.component("blog-text", {
template: "#box",
data() {
return {
cont: 0,
};
},
});
app.mount(".app");
本文来自投稿,不代表本站立场,如若转载,请注明出处:https://www.hui-xiang.cn/archives/173.html