创建一个小球组件:
<template>
<div class="ball" :style="style">
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return {};
},
props: {
color: {
type: String,
default: "white"
},
value: {
type: Number,
default: 0
},
target: {
type: Number,
target: 300
}
},
computed: {
style() {
return { background: this.color };
}
}
};
</script>
<style scoped>
.ball {
width: 100px;
height: 100px;
border-radius: 50%;
text-align: center;
line-height: 100px;
border: 1px solid red;
}
</style>
在App中使用这个小球组件:
<template>
<div id="app">
<ScrollBall color="red">红球</ScrollBall>
<ScrollBall color="blue">蓝球</ScrollBall>
</div>
</template>
<script>
import ScrollBall from "./components/ScrollBall.vue";
export default {
name: "app",
data() {
return {};
},
components: {
ScrollBall
}
};
</script>
效果:
让球动起来的步骤。
起名字:
传值:
考虑一下,我们能去改变value的值吗?如下:
给父说一下,我要改位置了,改完位置再传给我,如下:
在父中得到球的位置:
测试:
上面的写法有点啰嗦,需要子通知父,子把新数据给父,父再传递给子,比较麻烦。
看如上代码:
:value 和 @input === v-model。
代码如下:
还有官方提供的一种写法:
效果:
Vue提供了上面的写法的语法糖,如下:
让球停下来:
用到的知识点:
- 组件的id 问题 _uid
- 属性问题 校验 -> 计算属性
- 双向通信 props+emit / v-model / .sync
- 数据的绑定问题 $refs 拿到组件内部的方法 来调用组件中的方法