Vue3组件化开发-每个佳丽都是组件
- 介绍
- 如何编写一个组件?
- 动态组件的编写
介绍
本文算是前几篇的最后一节,这个部分在你学习的时候,一定会有很多不明白的地方,这都不要紧。你只要课后敲出这些代码,能够和截图中一样的效果就算完成任务了。
如何编写一个组件?
Vue中一个最主要的特性,就是让你使用组件化进行开发。
页面上你看到的任何的东西,都可以写成组件。
先来看看如何编写一个静态的Vue组件,编写一个标题组件。
新建一个Demo5.html
文件,然后把Demo4.html的内容全部拷贝过来。为了方便书写,把<script>
标签的第一行前,声明一个变量,比如就叫做app
,声明完变量之后,就可以把mount
部分独立出来了。
const app=Vue.createApp({
//.....somting........
app.mount("#app")
有了app变量,可以非常方便的自定义组件并使用了。
比如现在写一个关于标题的组件。
app.component('my-title', {
template: '<h1 style="text-align:center">大宝剑城</h1>'
})
有了这个组件,就可以在app的模板部分使用了,比如我们放在template的最上面,代码如下:
template: `<div>
<my-title />
<!--...somting......-->
</div>`
此时完整代码如下:
<script>
const app = Vue.createApp({
data() {
return {
inputValue: '',
list: []
}
},
methods: {
handleAddItem() {
this.list.push(this.inputValue)
this.inputValue = ''
}
},
template: `<div>
<my-title/>
<input v-model="inputValue" />
<button v-on:click="handleAddItem">增加佳丽</button>
<ul>
<li v-for="(item, index) of list">[{{index}}]{{item}}</li>
</ul>
</div>`
})
app.component('my-title', {
template: '<h1 style="text-align:center;">大宝剑城</h1>'
})
app.mount("#app")
</script>
效果如下:
动态组件的编写
什么是动态组件?
也许我说的并不标准,我这里指的动态组件是显示内容不固定,通过父组件或者程序控制而输出的内容。
现在会了静态组件的基本使用方法,把之前我们写的的佳丽组件单独出来,写一个组件,这个组件会绑定一些props
,用于接受父组件传递过来的参数,然后动态显示出内容。
动态组件有一个关键的指令是 v-bind
,用这种方法,组件可以通过props
取得对应的值。
代码如下:
app.component('my-jiali', {
props: ['item', 'index'],
template: `<li >[{{index}}]-{{item}}</li>`
})
props
是一个数组,可以接受多个值。
有了my-jiali
组件后,就可以在app的template中使用了,方法如下:
<my-jiali
v-for="(item,index) of list"
v-bind:item="item"
v-bind:index="index"
/>
看一下效果:
这时候肯定会有小伙伴认为,这也没有减少代码的工作量哦,
第一是因为我们的代码还比较简单,
第二是组件的意义是降低程序的耦合性,让大规模开发编程可能。
比如一个页面,分成几个人开发,每个人写不同的模块,写好后拼凑在一起。
有了组件这就变的非常容易。
本文的内容稍微有点绕,如果你听不太懂也没关系,关键是把代码写出来,为了方便学习,这里给出Demo5.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>Document</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
inputValue: '',
list: []
}
},
methods: {
handleAddItem() {
this.list.push(this.inputValue)
this.inputValue = ''
}
},
template: `<div>
<my-title/>
<input v-model="inputValue" />
<button v-on:click="handleAddItem">增加佳丽</button>
<ul>
<my-jiali
v-for="(item, index) of list"
v-bind:item="item"
v-bind:index="index"
/>
</ul>
</div>`
})
app.component('my-title', {
template: '<h1 style="text-align:center;">大宝剑城</h1>'
})
app.component('my-jiali',{
props:['index','item'],
template: `<li>[{{index}}]-{{item}}</li>`
})
app.mount("#app")
</script>
</html>