vue之组件理解(一)
组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods 以及生命周期钩子等。仅有的例外是像 el 这样根实例特有的选项。
其中,一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝。
data: function () { return { count: 0 } }
使用组件为了更好的复用,相当于自定义标签,你可以进行任意次数的复用。
首先要明确自己组件的功能
比如实现两个按钮,一个喜欢,一个不喜欢,每次点击可以记录次数。当点击按钮时,每个组件会各自独立维护它的count,每使用一个组件都会有一个新的实例被创建。
// 调用button组件 <hello-world heading="Likes" color="green"></hello-world> <hello-world heading="Dislikes" color="red"></hello-world>
<template id="button-component">
<div id="box">
<h1>{{ heading }}</h1>
<button @click="count += 1" :class="color">{{ count }}</button>
</div>
</template>
<script>
export default {
name: "button-component",
props:['heading','color'],
data:function () {
return{
count:0
}
}
}
</script>
<style scoped>
button{width: 50px;height: 30px;border-radius: 5px;}
.green{
background:green;
}
.red{
background: red;
}
</style>
出现的问题:对于直接绑定改变style的background值,
style="background: {{ color }}": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div style="{{ val }}">, use <div :style="val">.
不要忘了自己为了什么前进

浙公网安备 33010602011771号